Setting IsExpanded on a WPF TreeViewItem from a DataTrigger

前端 未结 2 1761
故里飘歌
故里飘歌 2021-01-12 10:42

I\'m trying to set the IsExpanded property of my TreeView items using a conditional template, in the XAML:



        
2条回答
  •  天命终不由人
    2021-01-12 11:13

    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:

    
        
            
        
    
    

    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:

    
    

    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;
    }
    

提交回复
热议问题