TextBox Text属性更改后ViewModle没有更新的问题

发布时间 2024-01-09 01:40:26作者: Shepherd_Over
<TextBox Text="{Binding Text}" />
partial class MainViewModel : ObservableObject
{
  [ObservableProperty]
  string text;  
}

如上所示,TextBox 绑定了 Mvvm中的Text属性,但是当TextBoxText文本发生更改后,mvvm中的Text属性却没有发生变更。
问题主要出在TextBox默认的通知模式是LostFocus,也就是失去焦点才会通知,若文本框赋值后,没有失去过焦点,则不会触发通知。

想要解决这个问题,只需要在TextBox的Text属性的绑定中,添加UpdateSourceTrigger属性,并将其赋值为PropertyChanged

如下:

<TextBox Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}" />