My earlier blog entry about a markup extension to simplify binding in an Infragistics TemplateField is good as far as it goes, but I wanted to add the ability to specify a Converter. This turned out to be far more complex than I thought it would be.
I thought it would be a matter of specifying a Converter property and adding it to the Binding. But when you add a StaticResource to the parameter list of a markup extension, it causes the sequence of events to change and stuff gets evaluated before you are ready. I want to thank this codeproject article for explaining it so well.
Let's take the earlier project and modify it the way I thought it would work. Open the XamDataGridTemplateField solution from my earlier entry. Add a new class called Converters and add a trivial converter to it like this.
namespace XamDataGridTemplatedField
class FontSizeConverter :IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
return value;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
return value;
}
}
Now open the TemplateBindings class and make these changes.
- Replace the Path member with a property
- Add a Converter property of type IValueConverter
- Add a default constructor
public TemplateBinding()
- In CreateBinding, assign the converter.
b.Converter = Converter;
Add a resources section referencing the new converter
<local:FontSizeConverter x:Key="FontSizeConverter"/>
</Window.Resources>
<TextBlock
Text="{igEditors:TemplateEditorValueBinding}" FontSize="{local:TemplateBinding Path=fontSize, Converter={StaticResource
FontSizeConverter}}"/>
class FontSizeConverter : MarkupExtension, IValueConverter
{
private static FontSizeConverter _converter;
if (value == null)
return value;
return value;
if (_converter == null)
_converter = new FontSizeConverter();
return _converter;
}
}
<TextBlock
Text="{igEditors:TemplateEditorValueBinding}" FontSize="{local:TemplateBinding Path=fontSize, Converter={local:FontSizeConverter}}"/>
<TextBlock
Text="{igEditors:TemplateEditorValueBinding}" FontSize="{local:TemplateBinding Path=fontSize, Converter={local:FontSizeConverter}}"/>
<TextBlock
Text="{igEditors:TemplateEditorValueBinding}" FontSize="{local:TemplateBinding fontSize, Converter={local:FontSizeConverter}}"/>