Home > .NET, Winforms > IValueConverter for Binding in WinForms

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.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: