11

In WPF it is easy to use a ValueConverter to format values etc, (in our case convert some numbers into a different unit, e.g km to miles)

I know it can be done in Winforms, but all my Googleing just brings up results for WPF and Silverlight.

Ian Ringrose
  • 51,220
  • 55
  • 213
  • 317

2 Answers2

21

You can use a TypeConverter if you're able and willing to decorate the data source property with a custom attribute.

Otherwise you have to attach to the Parse and Format events of a Binding object. This, unfortunately, eliminates using the designer for your binding for all but the simplest scenarios.

For example, let's say you wanted a TextBox bound to an integer column representing kilometers and you wanted the visual representation in miles:

In the constructor:

Binding bind = new Binding("Text", source, "PropertyName");

bind.Format += bind_Format;
bind.Parse += bind_Parse;

textBox.DataBindings.Add(bind);

...

void bind_Format(object sender, ConvertEventArgs e)
{
    int km = (int)e.Value;

    e.Value = ConvertKMToMiles(km).ToString();
}

void bind_Parse(object sender, ConvertEventArgs e)
{
    int miles = int.Parse((string)e.Value);

    e.Value = ConvertMilesToKM(miles);
}
Community
  • 1
  • 1
Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
  • 1
    It's worth mentioning that this technique will only cover scenarios where Binding objects are used and exposed. It won't work with grids and other complex binding controls, unless of course they have their own Format / Parse API. Therefore, there really isn't any "generic" way of using value converters within WinForms databinding mechanisms, unfortunately. – Crono Sep 10 '14 at 18:55
5

Another option is to have a specific ViewModel for the form which exposes data in the format you need to display on the form. You can easily achieve it by using AutoMapper and building your own Formatter.

This way you will have full support for designer too.

Giorgi
  • 30,270
  • 13
  • 89
  • 125