I would like to bind a textbox to a property of the window that is defined in the code behind file.
The binding succeeds when referencing the window when setting a RelativeSource using "FindAncestor" to find the window.
Why does it not work to reference the window by its name, just like I can bind the window's "Title" property?
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>
Code behind:
namespace WpfApplication123
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
XYZ = "XYZ!";
}
public string XYZ { get; set; }
}
}