I recently had the pleasure of presenting some rather advanced WPF concepts (along with some cool tips and tricks) to a group of smart folks. Unfortunately, I ran up against time constraints and was forced to drop the data binding portion of my talk. I’m a little bummed about not being able to show one cool trick that I use a lot, so here it is…
Call me lazy (really, I’m okay with it), but I’ve never been wild about having to declare my value converters as resources before using them. It’s just one extra step:
<Window.Resources> <src:MyConverter x:Key="MyConverter" /> </Window.Resources>
And then later the converter must be specified using a StaticResource reference, which incurs some overhead (albeit small overhead, in the grand scheme of things) for the resource resolution:
<TextBlock Text="{Binding SomePath, Converter={StaticResource MyConverter}}" />
I often choose to skip the middleman. Instead of using the StaticResource markup extension to look up a converter, I simply derive my value converter, itself, from MarkupExtension. Then I return an instance of it in the ProvideValue() override.
I have to assume there are plenty of others using this approach too. (It’s clever, afterall, but that’s about the extent of the hyperbole I’d grant it.) If you’re not one of them, I simply wanted to put it out there as a potential trick for your arsenal.
Below is a super simple example of a dummy converter (typically used to debug bindings) that does this:
public class DummyConverter : MarkupExtension, IValueConverter { private static DummyConverter _converter = null; public override object ProvideValue(IServiceProvider serviceProvider) { if (_converter == null) { _converter = new DummyConverter(); } return _converter; } #region IValueConverter Members public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value; // set breakpoint here to debug your binding } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return value; } #endregion }
The above class creates a singleton dummy converter that can be used across my app without any resource lookup. The XAML usage is now simply this:
<TextBlock Text="{Binding SomePath, Converter={src:DummyConverter}}" />
This is much better, to my lazy way of thinking.