In the following sample, when I type a new string into the TextBox and tab out the TextBlock is updated but the TextBox retains the value I typed in, instead being updated with the modified string. Any ideas how to change this behavior?
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App1"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}" Margin="106,240,261,187">
<StackPanel>
<TextBox Text="{Binding MyProp, Mode=TwoWay}"/>
<TextBlock Text="{Binding MyProp}"/>
</StackPanel>
</Grid>
</Page>
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public ViewModel()
{
MyProp = "asdf";
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetField<T>(ref T field, T value, string propertyName)
{
if (EqualityComparer<T>.Default.Equals(field, value)) return false;
field = value;
OnPropertyChanged(propertyName);
return true;
}
private string m_myProp;
public string MyProp
{
get { return m_myProp; }
set
{
m_myProp = value + "1";
OnPropertyChanged("MyProp");
}
}
}
The behavior you are seeing is somewhat the expected behavior.
When you tab out of your TextBox, the binding calls the MyProp setter. When you call OnPropertyChanged() you are still in the context of the original binding and only the other bindings will be notified of the change. (To verify it, have a break point on the Getter and see that it is only hit once after the OnPropertyChanged is called. The solution to this is to call the OnPropertyChanged after the intial binding has finished updating and this is achieved by calling the method async and not awaiting for it to return.
Replace the call to OnPropertyChanged(“MyProp”) with: