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 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.ActualWidthcan’t help. This is because width of each item is less thanTreeView.ActualWidthby 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 ofTreeViewwill be less thanTreeView.ActualWidthin this case.Here’s attached property:
…and markup:
Of course, provided solution isn’t universal – it assumes, that TreeView has
BorderandScrollViewer.