如何告诉我的ViewModel用户正在更改TextBox中的文本?

3

假设我有一个MVVM应用程序,我希望用户填写一个文本框,并且在他填写时,检查他是否已经输入了客户的姓氏。

以下是如何让我的ViewModel知道用户何时更改了ComboBox中的项目:

<ComboBox 
    ItemsSource="{Binding Customers}"
    ItemTemplate="{StaticResource CustomerComboBoxTemplate}"
    Margin="20"
    HorizontalAlignment="Left"
    SelectedItem="{Binding SelectedCustomer, Mode=TwoWay}"/>

以下是我如何让ViewModel在用户移动滑块时知道:

<Slider Minimum="0" 
        Margin="10"
        Width="400"
        IsSnapToTickEnabled="True"
        Maximum="{Binding HighestCustomerIndex, Mode=TwoWay}" 
        Value="{Binding SelectedCustomerIndex, Mode=TwoWay}"/>

以下是我如何让我的ViewModel知道当用户更改了TextBox中的文本并将焦点移开时:

<TextBox
    Width="200"
    Text="{Binding TypedCustomerName}"/>

但是我该如何让我的ViewModel知道用户在键入时已经更改了TextBox中的文本,例如:

伪代码(会导致错误,因为TextChanged是一个事件):

<TextBox
    Width="200"
    TextChanged="{Binding CurrentTextInTextBox}"/>
2个回答

11

如果你愿意,不仅可以在TextBox失去焦点时更新ViewModel,还可以设置它在用户键入时即时更新。TextBox的Text绑定属性上的UpdateSourceTrigger默认设置为LostFocus,而不是像大多数其他控件一样设置为PropertyChanged,但你可以在绑定中显式设置它。通过这样做,VM或M中的TypedCustomerName属性将随着在UI中更改而更新。

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

如果这不是你要找的,你也可以使用AttachedCommandBehaviors将TextChanged路由事件绑定到在你的视图模型中存在的ICommand。


1

文本框默认在失去焦点时更新。将UpdateSourceTrigger="PropertyChanged"设置为在用户输入时更新。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接