【发布时间】:2019-05-12 23:09:00
【问题描述】:
我正在开发一个利用 MVVM 范例的 UWP 应用。我的视图包含一个简单的 TextBox,它的 Text 属性绑定到相应的 ViewModel 属性:
<TextBox Text="{Binding Path=Radius, Mode=TwoWay}"/>
当然,我已将我的 ViewModel 分配给页面的DataContext:
public sealed partial class ExamplePage : Page
{
private ExamplePageVM viewModel;
public ExamplePage()
{
this.InitializeComponent();
viewModel = new ExamplePageVM();
DataContext = viewModel;
}
}
在 ViewModel 中,我执行某种输入验证,即。 e.如果用户在 TextBox 中插入了无效的浮点值,我想将 TextBox 重置为默认值(例如零):
class ExamplePageVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private float radius;
public string Radius
{
get => radius.ToString();
set
{
if (radius.ToString() != value)
{
if (!float.TryParse(value, out radius)) radius = 0;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Radius)));
}
}
}
}
更改 TextBox 中的值会导致按预期调用 setter。此外,PropertyChanged 事件也会被相应地调用。但是,在 setter 执行完成后,TextBox 仍然包含无效数据,这意味着视图没有正确更新。
根据this帖子的第一条评论,这个问题的解决方案是使用<TextBox Text="{x:Bind viewModel.Radius, Mode=TwoWay}"/>而不是上面显示的Binding方法。为什么呢?在这种情况下,Binding 和 x:Bind 有什么区别?
【问题讨论】: