我怎样才能知道我的视图模型,用户在文本框中更改文本?(How can I tell my ViewM

2019-09-16 12:04发布

所以我们可以说我有一个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
    Width="200"
    Text="{Binding TypedCustomerName}"/>

但是,我怎么当用户在TextBox更改文本,因为他的类型 ,比如像这样我的ViewModel知道:

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

<TextBox
    Width="200"
    TextChanged="{Binding CurrentTextInTextBox}"/>

Answer 1:

如果你喜欢,而不是只更新视图模型时,文本框失去焦点,您可以设置它来更新他们的类型。 该UpdateSourceTrigger在文本框的文本绑定属性默认替代的PropertyChanged像大多数其他控件设置为引发LostFocus,但是你可以在绑定明确设置它。 通过这样做,因为它在UI改变在VM或M的TypedCustomerName属性将更新。

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

如果这不是你要找的内容,你也可以使用AttachedCommandBehaviors绑定框TextChanged路由事件存在于您的视图模型的ICommand的。



Answer 2:

TextBoxex默认是对引发LostFocus更新。 设置UpdateSourceTrigger =“的PropertyChanged”更新为用户输入。



文章来源: How can I tell my ViewModel that the user is changing text in the TextBox?
标签: wpf mvvm binding