我想将文本框绑定到代码隐藏文件中定义的窗口属性。
使用“FindAncestor”设置RelativeSource 来查找窗口时,在引用窗口时绑定成功。
为什么按名称引用窗口不起作用,就像我可以绑定窗口的“标题”属性一样?
XAML:
<Window x:Class="WpfApplication123.MainWindow"
x:Name="MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF Binding Example" Height="180" Width="237">
<Grid>
<TextBox Height="23" HorizontalAlignment="Left" Margin="24,24,0,0" Name="textBox1" VerticalAlignment="Top" Width="136"
Text="{Binding ElementName=MyWindow, Path=Title}"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="24,53,0,0" Name="textBox2" VerticalAlignment="Top" Width="136"
Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=XYZ}"/>
<TextBox Height="23" HorizontalAlignment="Left" Margin="24,82,0,0" Name="textBox3" VerticalAlignment="Top" Width="136"
Text="{Binding ElementName=MyWindow, Path=XYZ}" />
</Grid>
</Window>
后面的代码:
namespace WpfApplication123
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
XYZ = "XYZ!";
}
public string XYZ { get; set; }
}
}