Unit testing Windows Forms controls & data binding

A quick tip from recent experience: If you're writing your own Windows Forms controls and trying to unit test them, data binding issues are likely to pop up at some point. When you put the controls on the form, data binding works like magic. But when you're instantiating the controls outside the form context, you suddenly realize data binding is totally dead. Whazzup?
It's all about binding context. Without going into details here, your controls need one. Normally, the form has a single binding context that gets set to all the controls on it (I think this happens during the autogenerated Controls.Add call in InitializeComponent, although I haven't really verified this). Well, just do a MyControl.BindingContext = new BindingContext(). If you need to simulate several controls that work together as if they were on the same form, assign the same BindingContext object to all of them.

Be Sociable, Share!

December 31, 2004 В· Jouni Heikniemi В· 2 Comments
Posted in: .NET

2 Responses

  1. cseeger - April 28, 2005

    thanks man – thanks so much!

  2. Tony - July 17, 2007

    Thanks man…
    This saved alot of headaches.

Leave a Reply