Saturday, May 5, 2007

Binding object event

When you bind a property to a field, they are two actions. First, object to gui (graphical user interface). Second, gui to object.



If you want to have control on both you need to subscribe to events.



The first event called Format do the first one, take the object information and format it to the gui. So let stay you have a property that has a ASCII character as INT. With the parser you can show to the screen the ASCII character as Char.



On the other side, the event called Parse take what the user input to the gui. When the gui send back the information to the object property's, it pass to the Parse event. You just need to convert back to INT in the Parse event and you are fine. The Parse event is raised after the control has changed focus, therefore after the Validating event and Validated event of the control.



Here is few important about the properties of the ConverEventArgs parameter of theses two events (Format and Parse both have Object sender and ConvertEventArgs as arguments) . The ConvertEventArgs has Value. This is the object value of what to display (or what to get back to the object depending your side of view). You have DesiredType that is the type of the Object, in our example above, it would be typeof(int).



The screenshot below is from Microsoft help about Parse and Value. It shows a simple example.

(Click to enlarge)

What if an error occur from a bad input of a user? Well, of course this should be threat and of course the value need not to crash the application. Hence, the framework is clever for this type of circumstance. If an exception is thrown from a binding event handler, the binding terminates the binding process for that control and force the control to refresh by refreshing the Format event (if the exception is from the Parse event). I say the framework is clever because you can raise yourself an error if you know that the value isn't in a good format or if the type is not good and cannot be converted than it will do it automatically without any help from you.

No comments: