Setting IsExpanded on a WPF TreeViewItem from a DataTrigger

前端 未结 2 1747
故里飘歌
故里飘歌 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:02

    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>
    
    0 讨论(0)
  • 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:

    <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;
    }
    
    0 讨论(0)
提交回复
热议问题