开发者

WPF StringFormat databinding text not appearing

开发者 https://www.devze.com 2023-01-17 13:38 出处:网络
I am trying to get the header text of a Treev开发者_开发技巧iewItem 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\

I am trying to get the header text of a Treev开发者_开发技巧iewItem 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.


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:

WPF StringFormat databinding text not appearing

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消