Archive

Archive for the ‘Winforms’ Category

IValueConverter for Binding in WinForms

I’m currently working on a Winforms project and there was a need if a product is in stock, the background of the ‘details product panel’ should be green, otherwise it should be red.
In xaml related technologies, this is an easy job. You bind the IsInStock (boolean) property on the BackColor property of the panel and create a converter which inherits from IValueConverter (InStockToColorConverter) which converts the boolean property to the correct color.

In Winforms you can create (in code) a binding too, but you can’t specify a converter to convert a boolean (IsInStock property) to a color. Todo that you should write a lot of code in your SelectionChanged event…
For easly tackle this job, I have written a CustomBinding class where you can specifiy a converter which implements the IValueConverter inferface, then you can do the job with one line of code:

DetailsPanel.DataBindings.Add(new CustomBinding("BackColor", ProductsBindingSource, "IsInStock",new InStockToColorConverter()));

You can download an example project and the full source here.

Advertisements