I\'m trying to set the IsExpanded
property of my TreeView
items using a conditional template, in the XAML
:
I had to do something similar, and I resolved it this way:
<TreeView ItemsSource="{Binding source}"
SnapsToDevicePixels="{Binding Path=myStatusToBool}"
>
<TreeView.ItemContainerStyle>
<Style>
<Setter Property="TreeViewItem.IsExpanded"
Value="False"
/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=SnapsToDevicePixels,RelativeSource={RelativeSource AncestorType=TreeView}}"
Value="True">
<Setter Property="TreeViewItem.IsExpanded"
Value="True"
/>
</DataTrigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.Resources>
.....
.....
</TreeView.Resources>
</TreeView>
There are a few things wrong here. The first is that you are setting the property TreeViewItem.IsSelected
on a HierarchicalDataTemplate
. This won't work. Instead, you're going to need to set an ItemContainerStyle
on the TreeView
:
<TreeView>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<!-- put logic for handling expansion here -->
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
You can't just put the Trigger
in here, however. Because of DependencyProperty value precedence, if your user clicks on the nodes to expand or collapse them, your triggers won't be #1 on the precedence list (that is a local value). Therefore, your'e best bet is to create a new IValueConverter
to convert from MyStatus
to a bool
. And then setup a TwoWay
binding in a Setter
in the Style
:
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded"
Value="{Binding MyStatus, Converter={StaticResource statusToBool}}" />
</Style>
And your converter:
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((MyStatus)value) == MyStatus.Opened;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return ((bool)value) ? MyStatus.Opened : MyStatus.Closed;
}