Search code examples
c#wpftreeviewtreeviewitem

WPF wrap header text on TreeViewItem


I have made a TreeView in WPF with 145px fixed width and all its child elements (TreeViewItems) has a header text that is wider than 145px, which means a horizontal scrollbar appears at the bottom of the TreeView.

I have managed to get rid of that scrollbar by adding:

ScrollViewer.HorizontalScrollBarVisibility="Hidden"

To my TreeView.

However, the header text that is too wide is now being hidden, so I want to wrap the header text so it fits into the TreeView with 145px width.

I have searched for solutions on this and tried some of those I found, but still haven't got it working and it's making me frustrated!

Here is my XAML code:

<TreeView ScrollViewer.HorizontalScrollBarVisibility="Hidden" Width="145" Name="tree_menu" >
   <TreeViewItem Header="This is a very long root element node text">
      <TreeViewItem Header="this is a very long child element node text" />
   </TreeViewItem>
</TreeView>

Solution

  • Maybe this works for you:

    <TreeView Name="tree_menu">
        <TreeView.Resources>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="HeaderTemplate">
                    <Setter.Value>
                        <DataTemplate>
                            <TextBlock Width="145"
                                       TextWrapping="Wrap"
                                       Text="{Binding}" />
                        </DataTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.Resources>
        <TreeViewItem Header="This is a very long root element node text">
            <TreeViewItem Header="this is a very long child element node text" />
        </TreeViewItem>
    </TreeView>