Reputation: 13
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; }
}
}
Upvotes: 1
Views: 1109
Reputation: 45096
You can just set this.DataContext = this and then bind to path.
You need
XYZ = "XYZ";
before the InitializeComponent
when the textbox is initialized XYZ is null
Upvotes: 1
Reputation: 11051
I never used a normal property, but my guess is you need to implement the INotifyPropertyChanged interface, and raise the property changed event in the setter of XYZ. The imho better approach is to use a dependency property directly.
Just make XYZ a dependency property and it should work.
Upvotes: 1