Simplify your Binding Converter with a Custom Markup Extension

Simplify your Binding Converter with a Custom Markup Extension

Value Converters are a useful addition to a WPF. The central idea is that if a value converter is specified in a binding, the source data is funneled to the converter before arriving at the binding destination.

Before you can use the converter in your XAML you need to add an instance of the converter to your XAML, usually in a resource section. Once you have the converter in a ResourceDictionary you can refer to it in the binding code.

 [XAML] 
<Window x:Class="ValueConverterTips.CustomMarkupTip"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:converters='clr-namespace:ValueConverterTips.Converters'
        Title="CusomMarkupTip"
        Height="300"
        Width="300">
  <Window.Resources>
    <converters:NumberToBrushConverter x:Key='brushConverter' />
 </Window.Resources>

  <Grid>
    <Ellipse Fill='{Binding SomeIntData, 
                    Converter={StaticResource brushConverter}}'
                    Width='10' Height='10' />
  </Grid>
</Window>
This is perfectly valid XAML and you will find it in thousands of WPF projects around the world. Programmers are always looking for a way to reduce the amount of code they need to write however and there is a way to simplify your code by creating your own MarkupExtension.

The key to this tip is that our converter class will derive from MarkupExtension

    Requires Free Membership to View

    When you register, you'll begin receiving targeted emails from my team of award-winning writers. Our goal is to provide a unique online resource for developers, architects and development managers tasked with building and maintaining enterprise applications using Visual Basic, C# and the Microsoft .NET platform.

    Hannah Smalltree, Editorial Director

    By submitting your registration information to SearchWinDevelopment.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchWinDevelopment.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

in addition to implementing the IValueConverter interface.

   
[C# code]
class NumberToBrushConverter : MarkupExtension, IValueConverter
  {
    private static NumberToBrushConverter _converter = null;

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
      // determine if we have an instance of converter
      // return converter to client
      return _converter ?? (_converter = new NumberToBrushConverter());
    }
    public object Convert(object value, Type targetType,
                          object parameter,CultureInfo culture)
    {

      return new SolidColorBrush(Colors.Orange);
    }

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

  }
Now that you have your custom MarkupExtension class you can remove the converter from the Resources sections and use the converter class directly.

<Window x:Class="ValueConverterTips.CustomMarkupTip"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:converters='clr-namespace:ValueConverterTips.Converters'
        Title="CustomMarkupTip" >
  
  <!-- no longer need the resources section -->

  <Grid>
    <Ellipse Fill='{Binding SomeIntData,  
             Converter={converters:NumberToBrushConverter}}'
             Width='10' Height='10' />
  </Grid>
</Window>

This was first published in March 2010

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.