Tracking ongoing text changes in your Universal app

This week I got the task to track input changes on some of our text fields for both auditing and validation. Usually you’re fine checking the new input once input is completed. And that’s exactly what the Windows Runtime (both Windows 8.1 and Windows Phone 8.1 RT) does for you: it updates the value in your binding after editing is completed and the TextBox control looses focus.

But the request clearly stated that any input change had to be logged. In a simple application with code-behind, you’d simply hook the TextChanged event and listen to the changes. However for every application containing more than a few pages, I usually use MVVM. So I need a way to get the event triggers in my viewmodel. And that’s where the Behaviors SDK comes in to help us out with a EventTriggerBehavior. As the name says, this one is for handling event triggers, like our TextChanged event.

<TextBox Width="200"
         Margin="10"
         Text="{Binding Text1, Mode=TwoWay}">
    <interactivity:Interaction.Behaviors>
        <core:EventTriggerBehavior EventName="TextChanged">
            <core:InvokeCommandAction Command="{Binding TextChangedCommand}" />
        </core:EventTriggerBehavior>
    </interactivity:Interaction.Behaviors>
</TextBox>

This will send TextChangedEventArgs to your ICommand, so be sure to accept the correct type. An alternative solution would be to provide your own behavior returning just the changed text, but in this scenario I didn’t mind getting all the info. Here I’ve used the MVVM Light’s RelayCommand as implementation of the ICommand interface.

public RelayCommand<TextChangedEventArgs> TextChangedCommand { get; private set; }

Feel free to check the sample code to verify how default binding works and what the result of the behavior is. Note that you can try to force the text you’re editing to a new value, but this only works once while in edit mode. So it might not be a wise action to try correct your user while he’s typing. Pretty sure there are workarounds here, but I didn’t bother looking for them as it was not a requirement.

Update: code moved to GitHub.

Licensed under CC BY-NC-SA 4.0; code samples licensed under MIT.
comments powered by Disqus
Built with Hugo - Based on Theme Stack designed by Jimmy