Search code examples
c#wpfivalueconvertervalueconverter

WPF ValueConverter - Standard return for unconvertible value


Over the course of the last year or so I have seen many different value converters for many different purposes, from many different authors. One thing that sticks out in my mind is the wide variance of the 'default' values that are returned by them. For example;

  public class MyConverter: IValueConverter
  {
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      // OK, we test for some undesirable, unconvertable situation, typically null...
      if (value == null)
      {
        // And here are a variety of 'defaults' that I have seen, these begin the most typical.
        return null;
        return DependencyProperty.UnsetValue;
        return Binding.DoNothing;
      }
        //...... other code.. whatever...
}}

So my question is, is there a 'standard' way to indicate that an input value can't be converted?


Solution

  • After much thinking and digging around, it seems that DependencyProperty.UnsetValue is the appropriate choice. I have moved everything in house over to this pattern with much success. Also, the text in the 'Remarks' section of this page indicates that I this is probably the best choice..

    There is also some discussion about returning the input value if a binding can't be converted, but this can easily "break" the binding system. Think of a case where the binding input is a 'string' and the output is a 'brush'. Returning a string is not going to work!