I have TreeView
, which displays some data using data templates. Here's XAML:
<TreeView Grid.Row="0" ItemsSource="{Binding Railways}" x:Name="tvDatawareObjects"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
</Style>
</TreeView.ItemContainerStyle>
<TreeView.Resources>
<!-- other templates here... -->
<HierarchicalDataTemplate DataType="{x:Type viewModels:ProjectViewModel}" ItemsSource="{Binding Phases}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding Model.Code}" FontWeight="DemiBold" />
<TextBlock Text="{Binding Model.Title}" TextWrapping="Wrap" Foreground="Gray" Grid.Row="1" />
</Grid>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type viewModels:CollectionViewModel}" ItemsSource="{Binding Items}">
<TextBlock Text="{Binding CollectionName}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
Text wrapping for <TextBlock Text="{Binding Model.Title}" TextWrapping="Wrap" Foreground="Gray" Grid.Row="1" />
doesn't work. What am I doing wrong?
I believe the
TextBlock
isn't wrapping because it doesn't have a defined width. The grid column that theTextBlock
is in has a * width which will grow as theTextBlock
grows in width. Try setting a width on theTextBlock
or the column and see if the change causes theTextBlock
to wrap.Update:
To be more specific, the problem is that the
TreeViewItem
will size itself to the size of its contents, theColumnDefinition
will fill the (infinitely) available space and theTextBlock
, with no width restriction, will never wrap. This post does a good job of describing how the TreeViewItem behaves. To sum it up: the content area of theTreeViewItem
is set to 'Auto' so it will grow to fit the contents. To explicitly set the width of theTreeViewItem
try binding yourColumnDefinition
width to theTreeView
'sActualWidth
.XAML:
try this
I did it. :)
Accordind to the link, provided in the Dan's answer, the reason is lying in the default TreeViewItemTemplate.
Unfortunately, simple binding to
TreeView.ActualWidth
can't help. This is because width of each item is less thanTreeView.ActualWidth
by definition - items are rendered with some horizontal offset, depending on their level.Hence, to solve the problem, I need to calculate width of item like this:
To be more precise, I need
ScrollViewer.ViewportWidth
, so as TreeViewContent might be scrolled vertically, and visible area ofTreeView
will be less thanTreeView.ActualWidth
in this case.Here's attached property:
...and markup:
Of course, provided solution isn't universal - it assumes, that TreeView has
Border
andScrollViewer
.