Silverlight TextBox AutoComit Behaviour

Standard Silverlight TextBox control is very useful but has one strange behavior: if you use TwoWay data binding and bind some property to controls Text property, when users type text into the control, this change is not propagated to the bound property until the control loses its focus.  

This can be very annoying if you have MVVM application and you have some kind of real-time filter that needs to update some data as-you-type.  

In TwoWay bindings, changes to the target automatically update the source, except when binding to the Text property of a TextBox. In this case, the update occurs when the TextBox loses focus (in case of element to element binding the text box behaviour is normal) .  

You can disable automatic source updates and update the source at times of your choosing. For example, you can do this to validate user input from multiple controls before you update the bound data sources.  

You must update the source for each binding individually, however. To update a binding, first call the FrameworkElement.GetBindingExpression method of a target element, passing in the target DependencyProperty. You can then use the return value to call the BindingExpression.UpdateSource method. The following example code demonstrates this process  

 Problem is that TextBox control does not call BindingExpression.UpdateSource when its Text property is changed so we have to do that manually in order to fix this issue.The AutoComit Behavior for textbox control is now part of NanoVMSupport Library (Lib for MVVM)  

public class AutoCommit : Behavior<TextBox>
    protected override void OnAttached()
        AssociatedObject.TextChanged += AssociatedObjectOnTextChanged;

    private void AssociatedObjectOnTextChanged(object sender, TextChangedEventArgs args)
        var bindingExpr = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
        if(bindingExpr != null) bindingExpr.UpdateSource();

    protected override void OnDetaching()
        AssociatedObject.TextChanged -= AssociatedObjectOnTextChanged;

And the xaml is  

<TextBox Text=”{Binding SearchText,Mode=TwoWay}”> 

Another approach to solve this issue is to create TextBoxEx class drived from TextBox.With this approach the xaml size will be highly reduced as for each text box in your application it would save around 90 chars in xaml.

public class TextBoxEx : TextBox
    public TextBoxEx()
        this.Loaded += new RoutedEventHandler(TextBoxEx_Loaded);

    void TextBoxEx_Loaded(object sender, RoutedEventArgs e)
        this.TextChanged += new TextChangedEventHandler(TextBoxEx_TextChanged);

    void TextBoxEx_TextChanged(object sender, TextChangedEventArgs e)
        var source = sender as TextBox;
        if (source != null)
            var bindingExpression = source.GetBindingExpression(TextBox.TextProperty);
            if (bindingExpression != null)


and xaml in this case is 

<ctrls:TextBoxEx Text=”{Binding SearchText,Mode=TwoWay}”/>

However the above behaviour give you more control of how text box behaves.

Nano ViewModel Support

Nano view model is very small library to build MVVM enabled Silverlight/WPF/WP7 based application.MVVM becomes more and more popular in fast few years and there are many implementations  like MVVM Light toolkit, Prism(Last Version), nRoute, or Caliburn however these libraries have too many features and keep on growing which could have adverse effect on you project in terms of performance etc.For example communication between view in MVVM Light Toolkit is based on silverlight messaging which may not be best if you working ithin single silverlight application.It can be used when you page have more than one silverlight application (xap files) which requires communication and what about if you are not intead to use some of the feature from the toolkits i.e you want just the MVVM but you end up with adding complete set of library in your project.What if you need some features from MVVM Toolkit and you too want to use prism library.

There are a number of benefits this pattern brings to both WPF and Silverlight development. Before you go on, ask yourself:

  • Do you need to share a project with a designer, and have the flexibility for design work and development work to happen near-simultaneously?
  • Do you require thorough unit testing for your solutions?
  • Is it important for you to have reusable components, both within and across projects in your organization?
  • Would you like more flexibility to change your user interface without having to refactor other logic in the code base?

MVVM is not just about resuability,blendability & testability however its very power and if used properly you could create low latency WPF based applications.If you want to know about the theory you may follow the post here or google it and you will find many discussions and articles on MVVM.

Below are the features supported by NanoVmSupport library

  • Minimum code in you view model.
  • No nead to have obvervable properties and extra code with each property.
  • Supports command implementation.
  • Command binding for all most all controls using EventToCommand implementation
  • Provision to set design time data for view model (supports blendability)
  • NanoVmSupport.Events libaray supports communication between two view models in you application.It is extracted from Prism library so you if you are familiar with prism its very easy for your.Please note that you don’t have to use prism to use this.If few months later support you want prism, you may exclude NanoVmSupport.Events library and your code will start using eventing from prism with just chnaging single line of initilization.
  • You can easyly write unit tests against your view models.

The sample silverlight application below (MVVM & library MVVM.Events) is the implement of NanoVMSupport & NanoVMsupport.Events.The source code for sample project and NanoVMSupport library can be downloaded from here and if required binaries are here.
[silverlight:,650, 550]

The sample folder in the source code also includes sample application code for silverlight and WPF.The WPF application is Auction Sniper for madbid which places your bids automaticaly based on some figures/process.
For communication between viewmodels check the documentation from prism or send me your queries in this post,for Microsoft Unity Application block click here.

MVVM common Issues & fixes in NanoVMSupport :

  • Standard Silverlight TextBox control is very useful but has one strange behavior: if you use TwoWay data binding and bind some property to controls Text property, when users type text into the control, this change is not propagated to the bound property until the control loses its focus. The AutoComit Behavior for textbox control is now part of NanoVMSupport Library (Lib for MVVM) for detail check this article “Silverlight TextBox AutoComit Behaviour“.
  • How to invalidate the CanExecute value : Suppose you have textbox and command button ,Can execute returns false if the length of text is zero otherwise it returns true and you have also used the above mentioned Auto Comit behaviour on text box.CanExecute will be re-evaluated when something interesting within the application’s window happens in WPF however in silverlight or with NanoVMSupport library you have to explictly update the ICommand.The one way of doing this is to change “RaisePropertyChange” method in ViewModelBase.cs as mentioned below
    protected void RaisePropertyChanged(string name)
        PropertyChanged.Raise(this, name);
        PropertyChanged.Raise(this, "");

    The code line PropertyChanged.Raise(this, “”); will refresh all the properties and icommands on view.But it may have performance issues if you have may properties and commands in viewmodal.The another recommended approach is to use following code in viewmodal

    public string SelectedText
        get { return Get(() => SelectedText); }
            Set(() => SelectedText, value);

    The code base.RaisePropertyChanged(“SearchCommand”); will invalidate the SearchCommand.

Silverlight Editors

An early days experiment to create silverlight based shape editor control and rich text editor control ..

Shape editor : click on “Image” button, select may drag,resize and change several properties of shapes.Some shapes like free hand drawing,text etc supports inline editing which will activate when you double click shape.
[silverlight:, 850, 650]

download shape editor source code

*Above control is just an experiment and may have buggs etc..

Word editor : experiment to Create RichTextBox ( silverlight based word) which allows basic text operations inclusing copy/past text etc to-from word,excel alone with formating and lot more..
[silverlight:, 800, 650]

*The code for this control was reflectored from Liquid RichTextBox and modified to incorporate other features. Liquid RichTextBox is free control to use in your application.

All these controls were created with silverlight 3 some were around 2009 and code may not to usefull as other new features are introduced with silverlight 4 which could be utilized in more efficient way.

Download RichTextBox source code

Silverlight WebSockets – Duplex Communication

A duplex communication system is a system composed of two connected parties or devices that can communicate with one another in both directions. Duplex communication is required when you need to send some data in the reverse direction i.e. from Server to client. For scenario purpose assume that something happens on server (some event is received from source) and message from server should be sent to connected clients. Off-course the solution should be highly scalable with low latency client and server.

Let’s talk about silverlight client in our scenario

 There could be couple of options with silverlight client demonstrated by Gill Cleeren In series of article “The duplex story: looking at duplex communication in Silverlight 4

Silverlight 4.0 now supports 3 different types of duplex communications

  • HTTP Polling Duplex: Duplex requires that the server can itself initiate communication, which is not supported by HTTP, HTTP Polling duplex (HTTP long polling, or Comet-style) protocol allows us to do bi-directional communication over HTTP. What happens behind the scenes is the following:
    • The Silverlight client initiates the communication by sending an initial request to the service.
    • After the client is registered with the service, it continuously starts polling the service for updates.
    • Whenever the service has new messages to send to the client, they are queued up until a new poll arrives from the client.

The HTTP Polling Duplex is therefore not real duplexing: it creates an illusion of duplex communication by polling (at network layer) so frequently that it looks as if the messages are pushed from the service to the client. If you still want to use this method here is the link for you to tune performance of http polling duplex.

  • Sockets: Socket is implemented through the use of a TcpListener, Being pure TCP endpoints, sockets are fast and true duplex communicators. However sockets in Silverlight can only work over ports between 4502 and 4534 making it unsuitable for duplex communication over the internet. Secondly you need to build policy server to provide clientaccesspolicy.xml for sockets.Note that Silverlight 4 also allows that the policy calls are made over HTTP.
  • net.tcp binding: this entirely new binding, added in Silverlight 4, also supports duplex communication. net.tcp combines advantages of both polling duplex and sockets. Its programming model is, just like polling duplex, based on WCF. That means that we can take advantage of automatic proxy generation inside Visual Studio.
  • Poll based communication: Not scalable, out of scope.

So what’s next?

 HTML 5 – WebSockets

Web socket protocol or WebSockets are “TCP for the Web,” a next-generation bidirectional communication technology for web applications being standardized in part of Web Applications 1.0.

The Web Sockets API enables web applications to handle bidirectional communications with server-side process in a straightforward way. Once you get a Web Socket connection, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler. The protocol is not raw TCP because it needs to provide the browser’s “same-origin” security model. It’s also not HTTP because web socket traffic differers from HTTP’s request-response model. you do need a new server implementation to communicate with web sockets .

web socket prototype is out now at or websocket msi from here

 for more information see :

Please also find the published websocket transport binding (Incomplete project)  here which i was trying to build using custom duplex WCF channel.

Silverlight Database

The Silverlight library in this article extends RIA service entities and provides save & load method to save/load entities directly into application storage (Isolation storage). The library supports dynamic quota management for application storage i.e. if an entity requires more space to store it will prompt user to confirm new size of quota store. The saving and loading supports asynchronous processing of entities with inbuilt compression which allows your application to provide non blocking UI. Library can be used to build online-offline mode based Silverlight applications without additional programming overheads.

Code to save RIA Entities in the storage space

EmployeeContext context = new EmployeeContext();
dataGrid.ItemSource = context.Employees;
Action<LoadOperation<Patient>> completeProcessing = delegate(LoadOperation<Patient> loadOp)
    if (!loadOp.HasError)
context.Load(context.GetEmployeesQuery(), completeProcessing, null);

Code to load RIA Entities from storage space

EmployeeContext context = new EmployeeContext();

You can also use the same library to save and load genric data you need to provide the filename to which the object set is saved whereas with Ria EntitySet the fileName is optional which is calculated based on the data type of entity.
Code to save List<string> into storge sapce

List<string> names = new List<string>();

Code to load List<string> into storge sapce

List<string> names = new List<string>();

Note: The Load method supports Asynchronous (default) and Synchronous operation where as Save method only supports Asynchronous operation.You can also override the Quota Management screen globally in your application and if not overrided the library will use in-built screen shown below (right image).

How it works : diagram is self explanatory..

Source code is now available here, Because of time constriants i was not able to comlete the code behind for the isolation storage screen above, however the library is now completed and published with silverlight unit test project.