How to make text wrap in a WPF TreeViewItem?

前端 未结 1 1200
后悔当初
后悔当初 2020-12-19 14:17

This time, my question is as simple as it sounds... how do you get text to wrap in a WPF TreeViewItem?

I have a simple HierarchicalDataTemplate

相关标签:
1条回答
  • 2020-12-19 14:44

    If you look at the default template of TreeViewItems you will see a Grid like this:

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition MinWidth="19"
                              Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <!-- ... -->
    

    As you can see the third column takes all available space while the others are on Auto, the header is placed in the second column inside a border:

    <Border Name="Bd"
            Grid.Column="1"
            ...
    

    This means that the column will become as large as the header, there is no restriction on it. Thus the header just gets bigger than the TreeView itself.

    If you add Grid.ColumnSpan="2" to this Border it will occupy the third column as well, which is restricted by how much space is left, hence the text will wrap; this will however extend the header across the whole width which might look a bit odd when selecting it.

    Of course you will also need to disable horizontal scrolling:

    <TreeView ScrollViewer.HorizontalScrollBarVisibility="Disabled" ...
    

    A screenshot

    0 讨论(0)
提交回复
热议问题