Click here to Skip to main content
15,867,568 members
Articles / Desktop Programming / WPF

Quick WPF tip: Generic Converter MarkupExtension

Rate me:
Please Sign up or sign in to vote.
4.50/5 (8 votes)
24 Apr 2010CPOL 24.1K   13   5
Quick WPF tip: Generic Converter MarkupExtension

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:
    C#
    public MyConverter : IValueConverter {}
  2. Implement Convert (and sometimes ConvertBack):
    C#
    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:
    XML
    <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:

C#
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:

XML
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:

C#
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:

C#
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:

XML
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

This article was originally posted at http://virtualdreams.com.br/blog?p=401

License

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


Written By
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.

Comments and Discussions

 
BugMarkupExtension method can be simplified Pin
Clifford Nelson1-Jun-16 6:47
Clifford Nelson1-Jun-16 6:47 
public override object  ProvideValue(IServiceProvider serviceProvider)
{
    if (_converter == null)
        _converter = new MyConverter();
    return _converter;
}


is overly complex. Use this instead:

public override object  ProvideValue(IServiceProvider serviceProvider)
{
    return this;
}


Never have had a problem with this much simpler implementation.

This is so simple, don't really see that a generic makes sense.
QuestionShorter Pin
hennsamc5-Aug-11 10:23
hennsamc5-Aug-11 10:23 
GeneralNot applicable to Silverlight (up to and including v4) Pin
Sidhe24-Apr-10 10:19
Sidhe24-Apr-10 10:19 
GeneralRe: Not applicable to Silverlight (up to and including v4) Pin
Roberto Sonnino24-Apr-10 10:49
Roberto Sonnino24-Apr-10 10:49 
GeneralThanks Pin
MetaEM5-Apr-10 20:48
MetaEM5-Apr-10 20:48 

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

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