所以,假设我有一个 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
Width="200"
Text="{Binding TypedCustomerName}"/>
但是,如何让我的ViewModel知道用户何时在键入时在TextBox中更改了文字,例如像这样的东西:
PSEUDO-CODE(因为TextChanged是一个事件导致错误):
<TextBox
Width="200"
TextChanged="{Binding CurrentTextInTextBox}"/>
答案 0 :(得分:11)
如果您愿意,可以在TextBox失去焦点时更新ViewModel,而不是在键入时将其设置为更新。默认情况下,TextBox的Text绑定属性上的UpdateSourceTrigger设置为LostFocus而不是像大多数其他控件一样设置为PropertyChanged,但是您可以在绑定中显式设置它。通过这样做,VM或M中的TypedCustomerName属性将在UI中更改时更新。
<TextBox
Width="200"
Text="{Binding TypedCustomerName, UpdateSourceTrigger=PropertyChanged}"/>
如果这不是您要查找的内容,您还可以使用AttachedCommandBehaviors将TextChanged路由事件绑定到View模型中存在的ICommand。
答案 1 :(得分:1)
TextBoxex默认是在LostFocus上更新。设置UpdateSourceTrigger =“PropertyChanged”以在用户输入时更新。