从 DataTrigger 在 WPF TreeViewItem 上设置 IsExpanded

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18403929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:29:13  来源:igfitidea点击:

Setting IsExpanded on a WPF TreeViewItem from a DataTrigger

c#wpfxamltreeviewtreeviewitem

提问by Suzanne Dupéron

I'm trying to set the IsExpandedproperty of my TreeViewitems using a conditional template, in the XAML:

我正在尝试使用条件模板设置IsExpanded我的TreeView项目的属性,在XAML

<DataTrigger Binding="{Binding MyStatus}" Value="Opened">
    <Setter TargetName="MyTextBlock" Property="Foreground" Value="Green"/>
    <Setter Property="TreeViewItem.IsExpanded" Value="True" />
</DataTrigger>

When I set the MyStatusproperty from the C# code, the colors are changed (so the DataTrigger works), but the nodes aren't expanded.

当我MyStatus从 C# 代码设置属性时,颜色会发生变化(因此 DataTrigger 可以工作),但节点不会展开。

_myItems[0].MyStatus = MyStatus.Opened;

How can I set the TreeViewItem.IsExpandedproperty from a DataTrigger?

如何TreeViewItem.IsExpanded从 a设置属性DataTrigger

When I start the application, the colors are correctly set, but the green node isn't expanded:

当我启动应用程序时,颜色设置正确,但绿色节点没有展开:

Screenshot just after starting the application

启动应用程序后的屏幕截图

And after changing the value of _myItems[0].MyStatusand _myItems[1].MyStatus, the colors are changed accordingly, but the green node still isn't expanded.

并且更改_myItems[0].MyStatusand的值后_myItems[1].MyStatus,颜色也相应更改,但绿色节点仍未展开。

Screenshot after clicking the Button1

单击 Button1 后的屏幕截图

Full Code (XAML)

完整代码 (XAML)

The full code is a bit long, but it's 90% boilerplate.

完整的代码有点长,但它是 90% 的样板。

<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="150" Width="250">
    <DockPanel>
        <DockPanel.Resources>
            <HierarchicalDataTemplate ItemsSource="{Binding SubItems}" x:Key="MyTemplate">
                <StackPanel Orientation="Horizontal">
                    <!-- ... -->
                    <TextBlock x:Name="MyTextBlock" Foreground="Green" Text="{Binding Name}" />
                </StackPanel>

                <HierarchicalDataTemplate.Triggers>
                    <DataTrigger Binding="{Binding MyStatus}" Value="Closed">
                        <Setter TargetName="MyTextBlock" Property="Foreground" Value="Red"/>
                        <Setter Property="TreeViewItem.IsExpanded" Value="False" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding MyStatus}" Value="Opened">
                        <Setter TargetName="MyTextBlock" Property="Foreground" Value="Green"/>
                        <Setter Property="TreeViewItem.IsExpanded" Value="True" />
                    </DataTrigger>
                </HierarchicalDataTemplate.Triggers>
            </HierarchicalDataTemplate>
        </DockPanel.Resources>

        <Button Name="button1" Click="button1_Click" DockPanel.Dock="Top" Content="Button1"/>
        <TreeView Name="treeView1" ItemsSource="{Binding MyItems}" ItemTemplate="{StaticResource MyTemplate}"/>
    </DockPanel>
</Window>

Full Code (C#)

完整代码 (C#)

using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace WpfApplication6
{
    public partial class MainWindow : Window
    {
        private ObservableCollection<MyItemCollection> _myItems;

        public MainWindow() {
            InitializeComponent();

            _myItems = new ObservableCollection<MyItemCollection> {
                new MyItemCollection { Name = "Parent1", MyStatus = MyStatus.Closed, SubItems = { new MyItemCollection { Name = "Child1" } } },
                new MyItemCollection { Name = "Parent2", MyStatus = MyStatus.Opened, SubItems = { new MyItemCollection { Name = "Child2" } } }
            };

            DataContext = new {
                MyItems = _myItems
            };
        }

        private void button1_Click(object sender, RoutedEventArgs e) {
            _myItems[0].MyStatus = MyStatus.Opened;
            _myItems[1].MyStatus = MyStatus.Closed;
        }
    }

    public enum MyStatus
    {
        Closed,
        Opened
    }

    public class MyItemCollection : INotifyPropertyChanged
    {
        public MyItemCollection() {
            SubItems = new ObservableCollection<MyItemCollection>();
            _myStatus = MyStatus.Closed;
        }

        public string Name { get; set; }

        public ObservableCollection<MyItemCollection> SubItems { get; set; }

        private MyStatus _myStatus;
        public MyStatus MyStatus {
            get { return _myStatus; }
            set { _myStatus = value; NotifyPropertyChanged("MyStatus"); }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName) {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

回答by Abe Heidebrecht

There are a few things wrong here. The first is that you are setting the property TreeViewItem.IsSelectedon a HierarchicalDataTemplate. This won't work. Instead, you're going to need to set an ItemContainerStyleon the TreeView:

这里有一些错误。第一个是您TreeViewItem.IsSelectedHierarchicalDataTemplate. 这行不通。相反,你将需要设置ItemContainerStyleTreeView

<TreeView>
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
        <!-- put logic for handling expansion here -->
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

You can't just put the Triggerin here, however. Because of DependencyPropertyvalue 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 IValueConverterto convert from MyStatusto a bool. And then setup a TwoWaybinding in a Setterin the Style:

Trigger然而,你不能把它放在这里。由于DependencyPropertyvalue precedence,如果您的用户单击节点以展开或折叠它们,则您的触发器将不会在优先级列表中排名第一(即本地值)。因此,傻冒最好的方法是创建一个新的IValueConverter从转换MyStatusbool。然后TwoWay在 aSetter中设置一个绑定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;
}

回答by German Torres

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>