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