Mark
Mark

Reputation: 983

WPF StringFormat databinding text not appearing

I am trying to get the header text of a TreeviewItem to be set in the binding to an XML source. Everything is working fine except the only thing that appears in the header is the text I'm binding to and nothing else in the string format. Example:

<HierarchicalDataTemplate x:Key="LogDataTemp" ItemsSource="{Binding Path=log}">
    <TreeViewItem>
        <TreeViewItem.Header>
            <Binding Path="Attribute[level].Value" StringFormat="TEST \{0\}" />
        </TreeViewItem.Header>
    </TreeViewItem>
</HierarchicalDataTemplate>

In this case the level value appears but nothing else. I have tried dozens of different ways of approaching this and it seems that nothing works.

Upvotes: 0

Views: 2079

Answers (1)

Wonko the Sane
Wonko the Sane

Reputation: 10823

Don't escape the braces in the StringFormat. You want to apply the formatting to the 0th-element in your binding.

For instance, with a simple property called "Level":

        <TextBlock x:Name="txtUnformatted" Grid.Row="0" Foreground="White" >
            <TextBlock.Text>
                <Binding Path="Level" />
            </TextBlock.Text>
        </TextBlock>

        <TextBlock x:Name="txtFormatted" Grid.Row="1" Foreground="White">
            <TextBlock.Text>
                <Binding Path="Level" StringFormat="Test {0:000000}" />
            </TextBlock.Text>
        </TextBlock>

And the result is something like:
alt text

Update

Also, the default implementation of the Header, when you don't add any controls, is a simple ContentPresenter, which doesn't apply formatting. To work around this, simply put a TextBlock into the header, and bind the text you want formatted to that.

<HierarchicalDataTemplate x:Key="LogDataTemp" ItemsSource="{Binding Path=log}">
    <TreeViewItem>
        <TreeViewItem.Header>
            <TextBlock>
                <TextBlock.Text>
                     <Binding Path="Attribute[level].Value" 
                              StringFormat="TEST {0}" />
                </TextBlock.Text>
            </TextBlock>
        </TreeViewItem.Header>
    </TreeViewItem>
</HierarchicalDataTemplate>

It is perfectly acceptable (and commonly done) to put controls into a header control (for instance, a grid containing an image and a label). The beauty of WPF.

Upvotes: 2

Related Questions