Click here to Skip to main content
Click here to Skip to main content

Quick WPF tip: Generic Converter MarkupExtension

By , 24 Apr 2010
Rate this:
Please Sign up or sign in to vote.

Hey there!

It’s been quite a while since the last English post – XAMLCast has been taking much of my blogging time. :-)

Today’s tip is an expansion of a method originally developed by Dr. WPF in this post: http://www.drwpf.com/blog/Home/tabid/36/EntryID/48/Default.aspx.

Usually, when working with Converters in WPF/SL, we always follow the same steps:

  1. Create a class that derives from IValueConverter:
    public MyConverter : IValueConverter {}
  2. Implement Convert (and sometimes ConvertBack):
    public object Convert(object value, Type  targetType, 
    	object parameter,  System.Globalization.CultureInfo culture)
    {
      // convert and return something
    }
  3. Instantiate the converter as a resource and use it:
    <ResourceDictionary ...>
        <local:MyConverter x:Key="TheConverter" />
    </ResourceDictionary>
    ...
    {Binding Converter={StaticResource TheConverter} ...}

Well, it works but it’s not a compact syntax. Following Dr. WPF’s idea, we can use a MarkupExtension to replace the StaticResource by a static instance of the Converter:

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;
    }
}

Usage:

xmlns:conv="[Path to namespace that contains the converter]"
...
{Binding Converter={conv:MyConverter}}

Now that’s pretty!

The only problem is that with this method, you'd have to repeat the implementation of the ProvideValue for each converter you create, and we programmers hate repeating ourselves. :-)

One solution I found is to create a generic abstract class that will contain that implementation, and derive each converter from that class. It’s cleaner and works the same:

using System;
using System.Windows.Data;
using System.Windows.Markup;

namespace VirtualDreams.Converters
{
    [MarkupExtensionReturnType(typeof(IValueConverter))]
    public abstract class ConverterMarkupExtension<T> : 
	MarkupExtension where T : class, IValueConverter, new()
    {
        private static T _converter;

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            if (_converter == null)
            {
                _converter = new T();
            }
            return _converter;
        }
    }
}

Let’s apply it to MyConverter:

public class  MyConverter: ConverterMarkupExtension<MyConverter>, IValueConverter
{
    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)
    }
}

Usage:

xmlns:conv="[Path to namespace that contains the converter]"
...
{Binding Converter={conv:MyConverter}}

Simpler, less repetitive – that’s the way I like it!

Happy converting!

Roberto

This blog post is also available on

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Roberto Sonnino
Virtual Dreams
Brazil Brazil
Hi! I'm Roberto. I'm a Brazilian Engineering student at the University of São Paulo and the Ecole Centrale de Lille (France).
 
I've participated in the Imagine Cup competition and went to the world finals every year from 2005 to 2009. I also won the 1st place award in 2006, in India, for the Interface Design invitational, in 2007 in Korea, for the Embedded Development invitational, and in 2009 in Egypt for the Windows Mobile Award.
 
Currently I keep a blog (in English and Portuguese) at http://virtualdreams.com.br/blog/ and a weekly webcast about WPF and Silverlight (in Portuguese) at http://www.xamlcast.net.
Follow on   Twitter

Comments and Discussions

 
QuestionShorter Pinmemberhennsamc5-Aug-11 10:23 
GeneralNot applicable to Silverlight (up to and including v4) PinmemberSidhe24-Apr-10 10:19 
GeneralRe: Not applicable to Silverlight (up to and including v4) PinmemberRoberto Sonnino24-Apr-10 10:49 
GeneralThanks PinmemberMetaEM5-Apr-10 20:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140415.2 | Last Updated 24 Apr 2010
Article Copyright 2010 by Roberto Sonnino
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid