Tip

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

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.