WPF Value Converter via MarkupExtension

Dr. WPF had a great post about deriving a value converter from MarkupExtension to avoid having to declare the converter as a static resource before being able to access it. This is a very convenient way of providing a value converter with less steps. I extended his technique and created a generic abstract class that can be used to derive value converters from to avoid the repetitive code that I would need to remember per his approach.

Here’s the result:

    // Base class
    public abstract class ConverterMarkupExtension<T> : MarkupExtension, IValueConverter
    where T : class, new()
    {
        private static T m_converter = null;
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (m_converter == null)
            {
                m_converter = new T();
            }
            return m_converter;
        }
        #region IValueConverter Members
        public abstract object Convert(object value, Type targetType, 
            object parameter, System.Globalization.CultureInfo culture);
        
        public abstract object ConvertBack(object value, Type targetType, 
            object parameter, System.Globalization.CultureInfo culture);
        #endregion
    }
    //Sample derived class
    public class BytesToKBValueConverter : ConverterMarkupExtension
    {
        public override object Convert(object value, Type targetType, 
            object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null && value is double)
            {
                double bytes = System.Convert.ToDouble(value);
                return bytes / 1024.0d;
            }
            else
                return value;
        }
        public override object ConvertBack(object value, 
            Type targetType, object parameter, 
            System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }

…and a sample markup to use the value converter:

image 

This approach also made it easier to convert my existing value converters.

 

posted @ Thursday, March 19, 2009 11:42 PM

Print

Comments on this entry:

No comments posted yet.

Your comment:



 (will not be displayed)


 
 
 
Please add 7 and 1 and type the answer here:
 

Live Comment Preview:

 
«February»
SunMonTueWedThuFriSat
31123456
78910111213
14151617181920
21222324252627
28123456
78910111213