I have a ViewModel which contains an observable collection of items called AllNodesAndEntries
. Each item has a boolean property IsEnabled
. Now I want to show the items in a TreeView and bind the IsEnabled
property of each TreeViewItem to the IsEnabled
property of its underlying item of the ViewModel. How do I do that?
Here is my TreeView. There are two different types of items (Node
and Entry
), so I have one hierarchical and one normal data template.
<TreeView ItemsSource="{Binding AllNodesAndEntries}">
<TreeView.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="{x:Type local:Node}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local:Entry}">
<TextBlock Text="{Binding Name}""/>
</DataTemplate>
</TreeView.Resources>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<!-- How do I bind to TreeViewItem.IsEnabled to IsEnabled? -->
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
It seems I cannot do it inside TreeView.ItemContainerStyle
, because there I can only define setters. But setters don't allow binding the value...
Use the setter to bind the "IsEnabled" property to your "IsEnabled" item property of each TreeViewItem.
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsEnabled" Value="{Binding IsEnabled}"/>
</Style>
</TreeView.ItemContainerStyle>