我有一个依赖属性的一类从装饰器继承,像这样:在代码绑定没有反应到源对象改变
public class LoadingAdorner : Adorner
{
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof (string), typeof (LoadingAdorner), new PropertyMetadata(default(string)));
public string Text
{
get { return (string) GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty IsShowingProperty = DependencyProperty.Register("IsShowing", typeof (bool), typeof (LoadingAdorner), new PropertyMetadata(default(bool)));
...
}
装饰器的真的没有任何XAML,但我想文这个装饰者可以绑定到视图模型。所以,我在代码中创建绑定,在视图的构造函数,像这样:
private readonly LoadingAdorner _loading;
public MainWindow()
{
InitializeComponent();
_loading = new LoadingAdorner(MainPage);
var bind = new Binding("LoadingText"){Source = DataContext};
_loading.SetBinding(LoadingAdorner.TextProperty, bind);
}
DataContext的是我的视图模型,我的视图模型实现INotifyPropertyChanged,LoadingText是一个字符串属性,调用OnPropertyChanged等。在所有绑定XAML工作正常,但是,代码绑定没有。
我认为这是因为在创建绑定时,视图模型尚未设置为DataContext(它为null),因此在创建视图后在行上执行此操作。如果我使用Source = this将该绑定设置为我的视图上的属性,它就可以工作。
我的问题是,为什么XAML绑定能够响应源对象的变化,而代码绑定似乎不是?有没有适当的方法让我创建一个绑定,以便对XAML绑定类似的事情做出反应?
新的绑定(“DataContext.LoadingText”){Source = this}工作!谢谢!然而,我仍然不确定为什么忽略Source,并简单地将路径指定为LoadingText不起作用。我有同样的想法 - 省略源代码,它将默认为DataContext ... – 2012-08-08 14:16:59
@BrentYates:它会绑定到包含绑定属性*的对象对象的'DataContext' *,在您的案例中似乎是与“MainWindow”的'DataContext'不同,所以您需要将源代码设置为'MainWindow'来代替它的'DataContext'。 – 2012-08-08 14:20:09