views:

321

answers:

2

Most common way I encountered of specifying a value converter for a binding is to:
1. Create an instance of the value converter as a resource with a key.
2. Reference the instance using StaticResource markup extension:

<TextBlock Text="{Binding Converter={StaticResource myFormatter}" />

Q: Is there anything wrong with using static instance as follows:

<TextBlock Text="{Binding Path=Description, Converter={x:Static local:MyFormatter.Instance}}"/>

// where Instance is declared as:
public readonly static MyFormatter Instance = new MyFormatter();

In my case value converter is immutable.

Edit: another way is to turn the converter into an extension so that you specify the converter using markup extension format:

<TextBlock Text="{Binding Converter={local:MyFormatter}}"/>
A: 

As long as the formatter really has no state, this should be fine. It is not equivalent though. In the first case, you have an instance of the class for each instance of your XAML-based control. In the second, only one instance will ever be created.

PeterAllenWebb
Right, another difference is that static constructor (that initializes the static instance) will be invoked at the class instantiation, while resource-defined converter happens at the time of WPF component construction (roughly speaking).
Which raises a scary prospect that people would write converters with state - I don't want to EVER debug code like that! Pre-coffee, I can't imagine a justification.
Andy Dent
+1  A: 

Technically it will be fine, but in practice I don't like it:

  1. If you declare the converter as a resource, then you have a single point of reference. If you change the namespace or class name of the converter, then you only have a single place to update.

  2. If you declare it as static, then you need to bring the clr-namespace in at the top of each and every xaml file that uses the converter. If you declare it as a resource, you don't.

  3. {Binding Converter={StaticResource myFormatter} is much shorter and easier to read than the static one. In the long run, this will help you more than you might think.

Orion Edwards
Suppose I use the converter only once (I actually do), in that case declaring the resource + referencing resource will be more typing. But you have a point. +1
Well sure, but you'll probably have more than one valueConverter, and some of those other valueConverters will be re-used (and so you want them as resources)... and so you should probably put this one along with all the others so it's consistent :-)
Orion Edwards