WPF ValueConverter - Standard return for unconvertible value

A.R. picture A.R. · May 13, 2011 · Viewed 15.9k times · Source

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?

Answer

myermian picture myermian · Oct 10, 2011

According to MSDN - IValueConverter:

The data binding engine does not catch exceptions that are thrown by a user-supplied converter. Any exception that is thrown by the Convert method, or any uncaught exceptions that are thrown by methods that the Convert method calls, are treated as run-time errors. Handle anticipated problems by returning DependencyProperty.UnsetValue.

The key line is Handle anticipated problems by returning DependencyProperty.UnsetValue.