我有一个简单的对话框窗口,它继承自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)
...
某种原因导致当窗口被创建并且没有绑定错误时,该文本框的初始文本未设置为"some text"。
然而,如果我将数据上下文设置为StackPanel而不是Window:
<StackPanel DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}">
...
</StackPanel>
一切都如预期运行。
这两个方法的区别是什么?为什么第一种方法不起作用?
RelativeSource Self
绑定,而当设置SomeText
属性时,DataContext已经设置(因此您必须触发PropertyChanged事件)。RelativeSource AncestorType=Window
绑定稍后评估,此时SomeText
已经被设置,因此当设置DataContext时,绑定源属性已具有所需的值。 - Clemens