Yesterday I got to the point that most of my priority one tasks were done ahead of schedule so I have decided to go back to old controls and rewrite them to work with the MVVM pattern. I even got to an old argument with my co-worker Felix about using code behind for UI purposes (he is a firm believer in Expression Blend but for implementing Watermarks he decided to use code behind – I refactored it using this).
So after fixing the Watermark and the AutoCompleteBox that used a service to populate the items in the code behind (using this) I got down to the actual minor functionality tweaks. Like when the user presses enter in AutoCompleteBox or TextBox some Action is triggered. For the AutoCompleteBox I used the Attached Property Approach (I changed it a bit to be for KeyUp instead of KeyDown) just without the CommandArgument since the selected item was already with Data Binding. And it worked just fine.
But with TextBox this approach just didn’t work – because TextBox binds the data only when it is out of focus!
I found some more people with the same problem:
Go4Answers: TextBox TextChanged event doesn't cause data binding to update
Silverlight Forum: TextBox TextChanged event doesn't cause data binding to...
They used the behavior solution (which while browsing for solutions I missed (I guess I am turning lazy because in StackOverflow I would have gotten the right answer in the first page/answer)). I just decided to use the CommandArgument from Attached Property Approach (the same one I didn’t need for AutoCompleteBox):
Components:EnterKeyUp.CommandArgument="{Binding Path=Text,RelativeSource={RelativeSource Self}}">
The View Model:
{
get;
private set;
}
(using GalaSoft MvvmLight)
Now you can just use the value.
Update:
@yesez5 in the comments have added his blog post (in Spanish, or in English (using Google Translate)) about using a built-in behavior from the Prism Library (that way you don’t even have to add code implementations for Action triggers or Behaviors in your project).
Resources:
IBlog<Johan>: Silverlight Watermark TextBox Behavior
Peter Kuhn: Using the AutoCompleteBox
StackOverflow: Invoke Command When “ENTER” Key Is Pressed In XAML (and Answer)
Go4Answers: TextBox TextChanged event doesn't cause data binding to update
Silverlight Forum: TextBox TextChanged event doesn't cause data binding to...
Zoltan's Dev Corner: Binding update on TextBox.TextChanged event using Behaviors