WPF数据绑定自定义控件
问题描述:
因此,我花了大约两个小时的时间把我的头撞到桌子上,试图将所有我能想到的东西绑定到自定义控件上的属性,而没有任何效果。如果我有这样的事情:WPF数据绑定自定义控件
<Grid Name="Form1">
<mine:SomeControl MyProp="{Binding ElementName=Form1, Path=DataContext.Enable}"/>
<Button Click="toggleEnabled_Click"/>
</Grid>
public class TestPage : Page
{
private TestForm _form;
public TestPage()
{
InitializeComponent();
_form = new TestForm();
Form1.DataContext = _form;
}
public void toggleEnabled_Click(object sender, RoutedEventArgs e)
{
_form.Enable = !_form.Enable;
}
}
TESTFORM样子:
public class TestForm
{
private bool _enable;
public event PropertyChangedEventHandler PropertyChanged;
public bool Enable
{
get { return _enable; }
set { _enable = value; OnPropertyChanged("Enable"); }
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
而且我的控制是这样的:
<UserControl>
<TextBox Name="TestBox"/>
</UserControl>
public class SomeControl : UserControl
{
public static readonly DependencyProperty MyPropProperty =
DependencyProperty.Register("MyProp", typeof(bool), typeof(SomeControl));
public bool MyProp
{
get { return (bool)GetValue(MyPropProperty); }
set { SetValue(MyPropProperty, value); }
}
public SomeControl()
{
InitializeComponent();
DependencyPropertyDescriptor.FromProperty(MyPropProperty)
.AddValueChanged(this, Enable);
}
public void Enable(object sender, EventArgs e)
{
TestBox.IsEnabled = (bool)GetValue(MyPropProperty);
}
}
当我点击切换按钮时绝对没有任何反应。如果我在Enable
回调中放置一个断点,它将永远不会被触发,这是怎么回事?
答
如果Enabled
方法不会做的比设定,你可以删除它,并绑定TextBox.IsEnabled
直接propertou更多:如果你想保持这样要注册的方法的特性通过改变回调
<UserControl Name="control">
<TextBox IsEnabled="{Binding MyProp, ElementName=control}"/>
</UserControl>
UIPropertyMetadata
为依赖属性。
而且这种结合是多余的:
{Binding ElementName=Form1, Path=DataContext.Enable}
的DataContext
是继承的(如果你不将其设置在UserControl
(你应该永远不会做)!),所以你可以只使用:
{Binding Enable}
此外,如果遇到任何绑定问题:There are ways to debug them。
我的印象是'DependencyPropertyDescriptor.FromProperty(MyPropProperty).AddValueChanged(this,Enable);'会导致在该依赖属性发生任何变化时调用Enable?另外,这是对我实际做的事情的一个简单的简化。它恰好代表了这个问题。 – FlyingStreudel 2012-07-24 18:37:41
@FlyingStreudel:哦,我扫描了你的密码,但错过了你通过它作为参考。不要使用描述符,在注册DP时添加一个更改回调的属性。 (使用相应的[元数据构造函数](http://msdn.microsoft.com/en-us/library/system.windows.uipropertymetadata.aspx))。 – 2012-07-24 18:41:07
虽然这是静态的?它如何引用当前实例上的控件? – FlyingStreudel 2012-07-24 18:41:54