StringFormat bindings only work when the target type is string

24 Jan 2013

Recently I had a problem putting some text into a WPF MenuItem. The binding in the Xaml was something like

<MenuItem Header="{Binding FileName, StringFormat='Open {0}'}" Command="{Binding Open}"/>`

It turned out that it wasn’t working because Header is a Content property, but the StringFormat binding extension only works when the target of the binding is of type string, such as TextBox.Text.
I’d never seen this mentioned anywhere before hitting this problem.

So, for a MenuItem you need to use the HeaderStringFormat property instead. E.g.

 <MenuItem Header="{Binding FileName}" HeaderStringFormat="Open {0}" Command="{Binding Open}"/>

For other controls you may need to set the Content property to a TextBlock and then bind to the Text property of that.