I have a TreeView
which is bound to a hierarchical collection of complex type.
<TreeView Name="treeCategories" SelectedValuePath="{Binding SelectedCategory, RelativeSource={RelativeSource AncestorType=UserControl}}">
<HierarchicalDataTemplate DataType="{x:Type LocalCategories:BaseCategory}" ItemsSource="{Binding Subcategories}">
<TextBlock Text="{Binding DisplayName}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
The hierarchical rendering now works fine, but I can't get the tree to pre-select a 'current item'. The current item is a dependency property of the User Control, defined as
public BaseCategory SelectedCategory { .. }
I have ensured that it has value, although I am not 100% sure when this value is set - before or after the tree is rendered? If it is after, then that would explain the problem.
I have tried:
SelectedValuePath="{Binding SelectedCategory, RelativeSource={RelativeSource AncestorType=UserControl}}"
and
SelectedValuePath="SelectedCategory"
but I can't get it to work.
How do I make the TreeView
preselect a 'current item', that is a dependency property of the User Control in which the tree is defined?
Edit
I am thinking, maybe I can use an item style to check if the item's underlying object is equal to my 'selected object'.
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedCategory, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="TreeViewItem.UnderlyingObject">
<Setter Property="IsSelected" Value="True" />
</DataTrigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
In the statements above, how can I access the underlying BaseCategory
object of TreeViewItem
so that I can do comparison and use Data Triggers?