我正在开发一个利用 MVVM 范例的 UWP 应用程序。我的 View 包含一个简单的文本框,它有一个 Text
绑定(bind)到相应 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 仍然包含无效数据,这意味着 View 未正确更新。
根据 this 上的第一条评论发布,此问题的解决方案是使用 <TextBox Text="{x:Bind viewModel.Radius, Mode=TwoWay}"/>
而不是 Binding
方法如上所示。为什么会这样? Binding
之间有什么区别?和 x:Bind
在这种情况下?
最佳答案
您可能想要自己设置 UpdateTrigger,因为 TextBox 通常会在调用失去焦点时更新源。
您可以更改行为 UpdateSourceTrigger=PropertyChanged。
<TextBox Text="{x:Bind AnswerText, UpdateSourceTrigger=PropertyChanged}"/>
<TextBox Text="{Binding AnswerText, UpdateSourceTrigger=PropertyChanged}"/>
如果这不起作用,您可能希望通过 keydown 事件防止输入与数字不同。您可以将其外包到用户控件中以供重用。
希望这对您有所帮助。
关于c# - 绑定(bind)与 x :Bind: Why isn't the view updated when using Binding?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53732967/