You've got to fix a couple of things before this will work.
First, you're binding expression isn't quite right. You specified that the binding source is the TextBox
by using the ElementName
. That's not correct. Your source should actually be the Window
since that's where your property exists. So, give your Window
a name, and change ElementName
to that Window
name. For example ..
<TextBox x:Name="TextBox_Test" HorizontalAlignment="Left" Height="23" Margin="49,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="288"
Text="{Binding ElementName=Window_Test, Path=TestProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
Second, your Window
needs to implement INotifyPropertyChanged
for changes on the source to be reflected on the target.
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _testProperty;
public string TestProperty
{
get { return _testProperty; }
set
{
_testProperty = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TestProperty"));
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
TestProperty = "Test";
}
public MainWindow()
{
InitializeComponent();
}
}
Note that I modified the class to implement the interface, and I raise the event in the property setter.
With these changes, your binding will work. I should note that this type of binding is a bit unusual. In cases like this, it's more common for the Window
to use a DependencyProperty
, or for you to bind to a non-UI class (A view model, for example). You may want to look into both as you learn about binding.
Dependency Properties
MVVM Pattern