XAML绑定不依赖于依赖属性?
我正在尝试(并且失败)在xaml中对依赖项属性进行数据绑定。 当我使用代码后,它工作正常,但不是在xaml中。
用户控件只是绑定到依赖项属性的TextBlock
:
而依赖属性是一个简单的字符串:
public static readonly DependencyProperty TestProperty = DependencyProperty.Register("Test", typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT")); public string Test { get { return (string)GetValue(TestProperty); } set { SetValue(TestProperty, value); } }
我有一个常规属性,在主窗口中通常实现了INotifyPropertyChanged
。
private string _myText = "default"; public string MyText { get { return _myText; } set { _myText = value; NotifyPropertyChanged(); } }
到现在为止还挺好。 如果我将此属性绑定到主窗口上的TextBlock
,一切正常。 如果MyText
发生更改并且一切都在世界范围内,则文本会正确更新。
但是,如果我在用户控件上执行相同的操作,则不会发生任何事情。
而现在有趣的部分是,如果我在代码背后执行相同的绑定就可以了!
TheControl.SetBinding(MyControl.TestProperty, new Binding { Source = DataContext, Path = new PropertyPath("MyText"), Mode = BindingMode.TwoWay });
为什么它不能在xaml中运行?
依赖项属性声明必须如下所示:
public static readonly DependencyProperty TestProperty = DependencyProperty.Register( "Test", typeof(string), typeof(MyControl), new PropertyMetadata("DEFAULT")); public string Test { get { return (string)GetValue(TestProperty); } set { SetValue(TestProperty, value); } }
UserControl的XAML中的绑定必须将控件实例设置为源对象,例如通过设置Bindings的RelativeSource
属性:
同样非常重要的是, 永远不要在其构造函数中设置UserControl的DataContext
。 我确定有类似的东西
DataContext = this;
删除它,因为它有效地阻止从UserConrol的父级inheritanceDataContext。
通过在后面的代码中的Binding中设置Source = DataContext
,您可以显式设置绑定源
隐式的绑定源是当前的DataContext。 但是,DataContext已经由UserControl的构造函数中的赋值设置为UserControl本身,并且不是窗口中inheritance的DataContext(即视图模型实例)。