Question

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}}"/>
Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top