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

WPF: Where to Put Value Converters?

Rate me:
Please Sign up or sign in to vote.
5.00/5 (24 votes)
31 Jan 2010Ms-PL2 min read 37K   19   5
The question this posts tries to address is: Where to put value converters?

The following tip is not new; it is based on this post and its comments. However, for the sake of completeness and for future reference, I bring here the final version.

The question this posts tries to address is: Where to put value converters?

Normal Solution

Usually, the common place to put value converters is in the resources section. With this in place, you can use the value converter with StaticResource syntax:

XML
<UserControl.Resources>
    <local:NotConverter x:Key="notConverter" />
</UserControl.Resources>

...

<StackPanel>
    <Button IsEnabled="{Binding Converter={StaticResource notConverter}}" />
</StackPanel>

This means that every time you want to use the value converter, you need to add it to the resources section. A better place is to put it in a global converters resource file, so the resource definition is only done once.

Creative Solution

In short, have your converter derive from MarkupExtension. This will avoid the question altogether. The complete solution provides a generic base class you should derive from, ConverterMarkupExtension. The advantages of deriving from this class are:

  • Your converter can be used as a markup extension. So the former code becomes:
    XML
    <StackPanel>
        <Button IsEnabled="{Binding Converter={local:notConverter}}" />
    </StackPanel>

    Specifically, no resource definition is needed. At all.

  • Only one instance of your converter is used to provide the value (sort of singleton).

    Note that every time the XAML compiler see a markup extension, it will create a new instance, BUT the following implementation always return the same single converter. If you are worried about all the short lived instances of the markup extension, just consider that using StaticResource (another markup extension) would have created them anyway. So there is no additional stress on memory consumption.

  • The base class provides default implementation for both IValueConverter and IMultiValueConverter methods. It throws NotImplementedException. This doesn’t seem much but helps shorten your converter code in the usual case when you implement only one conversion direction.

ConverterMarkupExtension, Short Version for Clarity

C#
public abstract class ConverterMarkupExtension<T> : MarkupExtension, IValueConverter,
    IMultiValueConverter
        where T : class, new()
    {
        private static T _converter = null; 

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

            return _converter;
        }

        #region IValueConverter Members

        public virtual object Convert(object value, Type targetType, object parameter,
            CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        public virtual object ConvertBack(object value, Type targetType,
            object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IMultiValueConverter Members
XML
...

#endregion

Here, you can get the full version of the code including lots of comments.

Using the Base Class

Following is an example of how to use ConverterMarkupExtension to implement your own converter:

C#
using System;
using System.Windows.Data;
using System.Globalization;

namespace WPF.Common
{
    /// <summary>
    /// Returns the negation of the given boolean value
    /// </summary>
    public class NotConverter : ConverterMarkupExtension<NotConverter>
    {
        public override object Convert(object value, Type targetType, object parameter,
            CultureInfo culture)
        {
            return !(bool)value;
        }
    }
}

Note that the value converter code remains practically the same, but you get the ability to use it as a markup extension and remove the "not implemented" section.

That’s it for now,
Arik Poznanski.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Software Developer (Senior) Verint
Israel Israel
Arik Poznanski is a senior software developer at Verint. He completed two B.Sc. degrees in Mathematics & Computer Science, summa cum laude, from the Technion in Israel.

Arik has extensive knowledge and experience in many Microsoft technologies, including .NET with C#, WPF, Silverlight, WinForms, Interop, COM/ATL programming, C++ Win32 programming and reverse engineering (assembly, IL).

Comments and Discussions

 
GeneralMy vote of 5 Pin
Michał Zalewski13-May-12 9:11
Michał Zalewski13-May-12 9:11 
Great idea! I just tested it on SL5 and work great!
QuestionMy vote of 5 Pin
egenis3-May-12 18:26
egenis3-May-12 18:26 
GeneralMy vote of 5 Pin
George Danila21-Nov-11 21:55
George Danila21-Nov-11 21:55 
GeneralMy vote of 5 Pin
Julien Villers31-Aug-11 0:03
professionalJulien Villers31-Aug-11 0:03 
GeneralMy vote of 1 Pin
gup1111-Feb-10 0:24
gup1111-Feb-10 0:24 

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.