En Español

There are times when you need to bind to a source but the source is not in the right format or otherwise needs to be manipulated.

For example, suppose, as we’ll show below, that you have a text entry and a button, but you only want the button enabled as long as there are one or more characters in the text entry, and of course if there is no text entered you want to disable button.

You could bind the button to a boolean property in your View Model and bind the text to another property and then on text changed you could test to see if there is text in the entry control and update the button. Yuck.

Value Converters For example, since “IsEnabled takes a boolean and the number of characters is an int, you need a way to convert that int into a bool. That is where value converters enter the picture.

The standard format for a value converter is

  • Implement IValueConverter
  • Implement a method Convert according to the interface
  • Implement a method ConvertBack according to the interface

Note that frequently you won’t need ConvertBack. In that case, implement it to return null or to throw a NotImplemented exception.

Our converter is pretty common. Since we want to convert an int to a bool, we’ll use the clever name IntToBoolConverter.

Next, we implement the first method, Convert

``` public class IntToBoolConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return (int)value!=0; }

```

And for ConvertBack we’re going to say if the value is true, return 1 otherwise return 0

``` public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return (bool)value ? 1 : 0; }

```

Using the Converter Our test code is as simple as can be. We have an entry which has no text in it, and a button whose IsEnabled value depends on binding to that control, but converting the int (how many characters) to a bool (enable or not).

We start by creating a ResourceDictionary, in this case at the top of the XAML page (which is very common for resources you are only going to use on one page)

```

```

Note: For resources you are going to use on many pages, you will want to put the resource in a ResourceDictionary in app.xaml. You will access it in exactly the same way as all the ResourceDictionaries in a project are merged at compile time.

Notice that we’ve assigned a key to the converter, this allows us to use the key in the XAML.

```