Question

So let's say I have an MVVM application and I want the user to fill out a TextBox and while he is filling it out, I want to check to see if he has typed in the last name of a customer yet.

Here is how I get my ViewModel to know when the user has changed the item in the ComboBox:

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

And here is how I get my ViewModel to know when the user has moved the Slider:

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

And here is how I get my ViewModel to know when the user has changed text in the TextBox and moved the focus away from the TextBox:

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

But how do I get my ViewModel to know when the user has changed text in the TextBox as he types, e.g. something like this:

PSEUDO-CODE (causes error since TextChanged is an event):

<TextBox
    Width="200"
    TextChanged="{Binding CurrentTextInTextBox}"/>
Was it helpful?

Solution

If you like, instead of only updating the ViewModel when the TextBox has lost focus, you can set it to update as they type. The UpdateSourceTrigger on the Text binding property of a TextBox is set to LostFocus by default instead of PropertyChanged like most other controls, however you can set it explicitly in the binding. By doing so, the TypedCustomerName property in the VM or M will update as it is changed in the UI.

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

If that's not what you're looking for, you could also use AttachedCommandBehaviors to bind the TextChanged routed event to an ICommand that exists in your View Model.

OTHER TIPS

TextBoxex default is to update on LostFocus. Set UpdateSourceTrigger="PropertyChanged" to update as user is typing.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top