Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Using an IValueConverter in a WPF MVVM application to select a UserControl/View

0.00/5 (No votes)
5 Sep 2012 10  
The IValueConverter can be used to select a View.

I answered a question a week or so ago, and was unable to point to an example of using an IValueConverter to select a View. I said I would publish something, so here it is.

One of the things a value converter can be used for is set the View. A good choice for the property to bind to is the ViewModel. The value converter can then set the View depending on the type of the ViewModel:

class ViewModelViewValueConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, 
    System.Globalization.CultureInfo culture)
  {
    if (value is UserControlViewModel1)
      return new View1();
    else if (value is UserControlViewModel2)
      return new View2();
    return null;
  }

  public object ConvertBack(object value, Type targetType, object parameter, 
    System.Globalization.CultureInfo culture)
  {
    throw new NotImplementedException();
  }
}

The application I have created to show this concept is really basic. Many of the class are empty, including the UserControl ViewModel classes, and the each of the UserControls only contain some text and no extra code behind. The ViewModel for the main form contains only two DelegateCommand properties to change the ViewModel in the ViewModel property to one of the two classes. If you are familiar with binding in WPF, you will see that the MainViewModel inherits from INotifyPropertyChanged since I need to be able to inform the View when the ViewModel property is changed. The only other significant part of the solution is the binding. I used a ContentControl in the ViewModel and bind to its Content property:

<ContentControl Content="{Binding ViewModel, 
                   Converter={StaticResource ValueConverter}}"
                HorizontalAlignment="Stretch"
                VerticalAlignment="Stretch" />

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here