在下面的示例中,当我在TextBox中键入一个新字符串并选项卡时,TextBlock会更新,但TextBox会保留我输入的值,而是使用修改后的字符串进行更新。任何想法如何改变这种行为?
<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");
}
}
}
答案 0 :(得分:2)
您所看到的行为有点像预期的行为。
当您退出TextBox时,绑定会调用MyProp setter。当您调用OnPropertyChanged()时,您仍然处于原始绑定的上下文中,并且只会通知其他绑定更改。 (为了验证它,在Getter上有一个断点,并且看到它只在OnPropertyChanged被调用后被击中一次。解决方案是在初始绑定完成更新后调用OnPropertyChanged并通过调用方法来实现异步而不等待它返回。
将对OnPropertyChanged(“MyProp”)的调用替换为:
Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, new
Windows.UI.Core.DispatchedHandler(() => { OnPropertyChanged("MyProp"); }));