从 DataTrigger 在 WPF TreeViewItem 上设置 IsExpanded [英] Setting IsExpanded on a WPF TreeViewItem from a DataTrigger

查看:36
本文介绍了从 DataTrigger 在 WPF TreeViewItem 上设置 IsExpanded的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

_myItems[0].MyStatus = MyStatus.Opened;

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

How can I set the TreeViewItem.IsExpanded property from a DataTrigger?

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

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

并且改变_myItems[0].MyStatus_myItems[1].MyStatus的值后,颜色也相应改变了,但绿色节点仍然不是't 展开.

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

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

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

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

完整代码 (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));
            }
        }
    }
}

推荐答案

这里有一些错误.第一个是您在 HierarchicalDataTemplate 上设置属性 TreeViewItem.IsSelected.这行不通.相反,您需要在 TreeView 上设置一个 ItemContainerStyle:

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>

但是,您不能将 Trigger 放在此处.由于DependencyProperty 值优先,如果您的用户单击节点要展开或折叠它们,您的触发器将不会在优先级列表中排名第一(即本地值).因此,最好的办法是创建一个新的 IValueConverter 以将 MyStatus 转换为 bool.然后在 StyleSetter 中设置一个 TwoWay 绑定:

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>

还有你的转换器:

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

这篇关于从 DataTrigger 在 WPF TreeViewItem 上设置 IsExpanded的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆