I write these code in mainpage.xaml
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel>
<TextBox x:Name="xxx" Text="{Binding Test}" TextChanged="xxx_TextChanged" />
<Button x:Name="click" Click="click_Click" Content="click" />
</StackPanel>
</Grid>
And these in mainpage.xaml.cs
private string test;
public string Test
{
get { return test; }
set
{
if (test != value)
{
test = value;
OnPropertyChanged("Test");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
// Constructor
public MainPage()
{
InitializeComponent();
}
private void xxx_TextChanged(object sender, TextChangedEventArgs e)
{
Debug.WriteLine(Test);
Debug.WriteLine(test);
}
But Test isn’t binded to textbox, when I write smth to textbox Test isn’t changed.
What I doing wrong and how to correct that ?
Try setting
BindingModeto TwoWay:The other thing I’ve noticed, is that your binding to work need
DataContextto be set, but you don’t do that in your example. One way to do this would be something like this:If staying in Xaml is preferred, you can use
RelativeSourceproperty to bind to your page in Xaml, without setting DataContext:Another thing,
Testwill be set not after every character you type in your TextBox, but after user will finish editing text, for example by switching active control to next one.