所以,假设我有一个 MVVM 应用程序,我希望用户填写 TextBox ,同时填写,我想查看他是否输入了客户的姓氏

以下是我如何让我的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:

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

但是,如何让我的ViewModel知道用户何时在键入时在TextBox中更改了文字,例如像这样的东西:

PSEUDO-CODE(因为TextChanged是一个事件导致错误):

<TextBox
    Width="200"
    TextChanged="{Binding CurrentTextInTextBox}"/>
有帮助吗?

解决方案

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

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

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

其他提示

TextBoxex默认是在LostFocus上更新。设置UpdateSourceTrigger =&quot; PropertyChanged&quot;在用户输入时更新。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top