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

WPF Display Value Converter

0.00/5 (No votes)
23 Jun 2016 1  
This presents a simple converter that supports binding to an object, but display of a property in that class.

Introduction

This simple IValueConverter allows binding to an object, then the actual binding is to a property or ToString() value in that class, specifying the name of property in the ConverterParameter.

Background

I was using IDataErrorInfo for a form, and some of the data in the ViewModel were objects. This form was a read-only form and I wanted to show any data issues. There was also an edit form where the values could be changed. I could have done some work to get the IDataErrorInfo to work, but it seemed like a IValueConverter was a better option since it could be used in many cases, and was actually very simple and easy to maintain.

The Converter

The IValueConverter handles OneWay Binding only since converters do not provide an interface to the class that would be updated for the ConvertBack method. It could be changed so that it would just return the new value and the property set accessor could update the value.

The Convert method handles two cases: where there is a value provided in the ConvertParameter and when there is not. If a ConvertParameter is not provided, then the ToString() method of the object is returned. If a ConvertParameter is provided, then reflection is used to get the value of the property with the name contained in the ConvertParameter:

internal class DisplayValueConverter : MarkupExtension, IValueConverter
{
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
  if (string.IsNullOrWhiteSpace(parameter?.ToString()))
  {
   return value?.ToString() ?? value;
  }
  else
  {
   if (value == null) return DependencyProperty.UnsetValue;
   var property = value.GetType().GetProperty(parameter.ToString());
   Debug.Assert(property != null,
        $"Could not find property {property} in class {value.GetType().Name}");
   return property.GetValue(value);
  }
 }

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

 public override object ProvideValue(IServiceProvider serviceProvider) { return this; }
}

The Sample

History

  • 16/06/23: Initial version

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