[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