NGTweet Part 11– Silverlight 5 UpdateSourceTrigger


In one of the earlier post on Data Validation of this NGTweet series I had demonstrated the use of IDataErrorInfo to validate data. While the post was sufficient to demonstrate the use of IDataErrorInfo, there was a slight shortcoming in that implementation. This was due to a limitation in the Silverlight 4 DataBinding. In order to fire the validation, we had to wait till the focus was lost from the text box because the binding fires for textbox control only on lost focus event. This limitation is applicable only in case of Silverlight. WPF supports firing the change notification for databound textbox as soon as the text is entered in the control.

Use UpdateSourceTrigger to update data source

Just to highlight what I said earlier, as you can see from the screenshot below, there is text entered in the textbox. But the send button is not enabled until the focus is lost from the textbox. From usability point of view this is not really user friendly. We would want the send button to be enabled as soon as some text is entered by the user.

Without UpdateSourceTrigger

If you are not using MVVM, then this is not a very big issue. You can write code in code behind file by subscribing to the TextChanged event. The MVVM purists who don’t believe in writing code in the code behind file have used tricks like adding a behaviour to the text box and updating the data source. But it was clearly a limitation of the Silverlight in itself that we were trying to address.

Not anymore. With the latest release of Silverlight 5 this issue has been addressed. The built in data binding supports a new mode for the UpdateSourceTrigger. If we set this to the value PropertyChanged the framework takes care of updating the data source.

                <TextBox Text="{Binding TweetText, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"

With that one change you can see the impact, the moment I enter any text the send button is enabled.

With UpdateSourceTrigger


This might not be a big change and people working on WPF wouldn’t feel much about it. But in Silverlight context it is very helpful. It makes life easier for MVVM practitioners. As mentioned earlier there are alternatives to overcome this shortcoming. Having it as part of the framework is more like a necessity. Its good to see that Silverlight is adding more and more features which makes life easier for MVVM developers.

As always the complete working solution is available for download at Dropbox.

Until next time Happy Programming Smile


No comments:

Post a Comment