Wpf – Binding StringFormat doesn’t seem to work correctly

bindingwpf

I have a DataGrid and an Expander like so:

<StackPanel>
<my:DataGrid Name="dataGrid1" AutoGenerateColumns="False"  ItemsSource="{Binding}">...</my:DataGrid>
<Expander Header="{Binding ElementName=dataGrid1, Path=SelectedItem.Name, StringFormat=Details of {0}}">...</Expander>
</StackPanel>

The binding is fine, but for some reason the string formatting will not work. It always displays only the value dataGrid1.SelectedItem.Name
I have also tried:

StringFormat=Details of \{0\}

which doesn't work.

I even tried just setting the HeaderStringFormat property of the Expander to "Details of {0}" but that doesn't format it either.

I was able to get this workaround to work though:

<Expander>
<Expander.Header>
<TextBox Text="{Binding ElementName=dataGrid1, Path=SelectedItem.Name, StringFormat=Details of {0}}"></TextBox>
</Expander.Header>
</Expander>

Does anyone know why StringFormat isn't working for the Header property?

Best Answer

According to http://codingcontext.wordpress.com/2008/11/17/headerformatstring-and-contentformatstring/, it looks like the HeaderStringFormat property isn't meant to be used with string format binding, but rather to specify the format to use when binding to an object that implements IFormattable.

Given that, I couldn't get string formatting to work directly in the binding expression, either, so that might just be a bug. You should try notifying Microsoft and maybe they'll fix it.

With your workaround, I would suggest using a TextBlock rather than a TextBox, since you probably don't want the user to be able to edit the text in the Expander header.

Related Topic