4. Data Bind to Anything

There are situations where
you need to data bind to a value and the value type or format does not
quite line up with what you need. The IValueConverter
interface allows your application to data bind to just about anything
including data that does not match the type expected for a particular
control.

As an example, let's say you have a field that takes values of either Yes or No. You could use a ListPicker but a CheckBox makes more sense since it is just two values. You can implement IValueConverter to convert true to a Yes value and No value to false (and vice versa) while still using standard data binding mechanisms.

In this section, we create a custom IValueConverter named HtmlToImageUriConverter.
This very simple converter parses the AppHub Feed html, previously
displayed as raw html text, into a URL that points to an image related
to the content. The URL is extracted from the HTML. Listing 4 shows the code for the converter.

The converter is somewhat
brittle in that it depends on the URL value to be the fourth string when
split, but one wouldn't expect the feed format to change very often,
and it makes for an interesting sample. The converter is made available
to the DatabindToAnything.xaml View via an xml namespace import:

The Binding.Converter parameter is configured to the added StaticResource to apply the converter for the Image object. Note that this sample also implements the LowProfileImageLoader for better performance as well as the PerformanceProgressBar to give better visual status to the user. Figure 6 shows the resulting output with a nice image instead of the raw HTML that was displayed previously.

Figure 6. AppHub feed with articles and corresponding images

In this section, data
binding concepts are extended to more real world scenarios while also
incorporating MVVM concepts. The next section provides a quick tour of
available encryption services in Windows Phone 7.