wpf

WPF: Is there a way to use a ValueConverter without defining a resource?


Is there a way to use a ValueConverter without defining it in a resource? As is the syntax is pretty verbose.


Solution

  • You can use a MarkupExtension to minimise the amount of XAML code required. E.g:

    public class  MyConverter: MarkupExtension, IValueConverter
    {
        private static MyConverter _converter;
    
        public object Convert(object  value, Type targetType, 
        object  parameter, System.Globalization.CultureInfo culture)
        {
            // convert and return something
        }
    
        public object  ConvertBack(object value, Type  targetType, 
        object parameter,  System.Globalization.CultureInfo culture)
        {
            // convert and return something (if needed)
        }
    
        public override object  ProvideValue(IServiceProvider serviceProvider)
        {
            if (_converter == null)
                _converter = new MyConverter();
            return _converter;
        }
    }
    

    You end up with a syntax like this:

    {Binding Converter={conv:MyConverter}}
    

    This approach has an added advantage of ensuring that all your converters are singletons.

    This article does a great job of explaining the concept and provides sample code.