Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding StringFormat doesn't seem to work correctly

Tags:

binding

wpf

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?

like image 978
Adam Avatar asked Apr 11 '09 22:04

Adam


2 Answers

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.

like image 84
Andy Avatar answered Sep 22 '22 22:09

Andy


I've also encountered the same issue and after reading some articles, trying all kinds of ContentStringFormat and HeaderStringFormat I've just decided to do the next thing:

<Expander Grid.Row="1" Padding="4">
                <Expander.Header>
                <TextBlock Text="{Binding ElementName=cbCategory, Path=SelectedItem.CategoryName, StringFormat='FORMATTED &quot;{0}&quot;'}"/>
                </Expander.Header>
like image 33
netaholic Avatar answered Sep 21 '22 22:09

netaholic