Search code examples
wpfxamlvalueconverter

Is using value converters to generate GUI-friendly strings a misuse of value converters?


Currently, I use value converters to generate user-friendly strings for the GUI. As an example, I have a window that displays the number of available entities in the status bar. The Viewmodel simply has an int dependency property that the calling code can set, and then on the binding for the textbox that displays the number of entities, I specify the int dependency property and a value converter that changes "x" into "x entities available".

My code is starting to become littered with these converters, and I have a large number of annoying resource declarations in my XAML, and yet I like them because all the GUI-specific string formatting is being isolated in the converters and the calling code doesn't have to worry about it. But still, I wonder if this is not the purpose that value converters were made for.


Solution

  • As @slugster mentioned, the StringFormat property can be specified in the Binding, although it is available as of .NET 3.5sp1. This is how I typically specify these types of formats:

    <TextBlock Text="{Binding x, StringFormat={}{0} entities available.}" />
    

    This enables your ViewModels to only specify the data that is required to display, and easily allows the view to format the data however it wants. IMO, this is the cleanest line of separation between the view and the viewmodel.

    Note that the {} is required to escape the {0} as it is the first element after the StringFormat property.