PropertyManager - cool trick

It always amazes me to see the cool tricks one can do using Data binding. Be it simply binding a property of a control or complex binding master/child views with data entry, etc. So, here's a small cool trick about property binding.

In Winforms, you can bind any property of any control to another property of a control - just a 1 line code. e.g. Say, you have a Textbox on the form where a user can enter some text. Below the Textbox say you have a Label that shows a count of the number of characters the user has typed already. One way to do this would be to hook on to the TextChanged event of the textBox and calculate the length of the Text in the Textbox and then update the Label text. Another "cooler" way to do this would be through binding. This line does the trick:

label.DataBindings.Add("Text", textBox, "Text.Length");

This line binds the Text property of the label to the Length of the Text property of the textBox! Typing in text in the textBox will update the text of the Label. It's that simple!

How does this work? For this kind of simple property binding, there is a PropertManager that manages this binding. The PropertyManager hooks on to the *Changed event internally and is notified of any changes.

Happy Binding!