Reputation:
I'm trying to bind a Textbox to a string defined in the .cs file using the followings:
Xaml Code:
<TextBox x:Name="textBox_Data" CaretBrush="DodgerBlue" Foreground="White" Text="{Binding Data}" HorizontalAlignment="Left" Height="22" Margin="10,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="123" SelectionChanged="textBox_Data_SelectionChanged"/>
Xaml.cs Code:
public string Data{get; set;}
But the string isn't updating...
Upvotes: 0
Views: 37
Reputation: 6452
{Binding Data}
refer the DataContext
of current element (or to one of ancestors).
one way
for refer the xaml.xxx.cs you need refer the Window element, you can give him a name:
<Window x:Name="window" x:Class=...
and change the Binding to refer element name:
Text="{Binding Data, ElementName=window}"
Second way
you can also inject all window class to current DataContext:
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}" x:Class=...
Now you can leave the original expression:
Text="{Binding Data}"
Third way
You can also set DataContext from the code. do not change anything in xaml, and add in this line (DataContext = this;
) at end of constructor:
public xyz() {
InitializeComponent();
//...
DataContext = this;
}
Upvotes: 0
Reputation: 817
Your class has to derive from INotifyPropertyChanged
and you have to implement it in your property setter
Or more pleasant way: Install PropertyChanged.Fody
from nuget. You can read more about it here: https://github.com/Fody/PropertyChanged
And keep in mind, not to use this.DataContext=this;
when initializing your window, use binding as dovid suggests.
Upvotes: 1