【发布时间】:2015-03-09 12:18:48
【问题描述】:
我有一个从 Window 继承的简单对话框窗口,我在 XAML 中设置它的 DataContext,如下所示:
<Window x:Class="MyProject.MyDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
...>
<StackPanel>
<TextBox Text="{Binding SomeText}"/>
...
</StackPanel>
</Window>
这是我显示此对话框的方式:
var dialog = new MyWindow();
MyWindow.SomeText = "some text";
if (dialog.ShowDialog() == true)
...
由于某些原因,在创建窗口并且没有绑定错误时,不会将文本框的初始文本设置为“某些文本”。
但是,如果我为 StackPanel 而不是 Window 设置数据上下文:
<StackPanel DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}">
...
</StackPanel>
一切都按预期进行。
这两者有什么区别?为什么第一种方法不起作用?
【问题讨论】:
-
区别仅在于时间。虽然
RelativeSource Self绑定在 Window 构造函数的执行期间被评估,但在设置SomeText属性时已经设置了 DataContext(因此您必须触发 PropertyChanged 事件)。RelativeSource AncestorType=Window绑定稍后评估,在SomeText已经设置之后,所以当 DataContext 被设置时,绑定源属性已经具有所需的值。