使用 HierarchicalDataTemplate 的 WPF MVVM 树视图未更新

本文关键字:视图 更新 MVVM HierarchicalDataTemplate WPF 使用 | 更新日期: 2023-09-27 18:28:30

所以我长期以来一直在努力让我的 TreeView 正确更新,所以我问是否有人可以告诉我为什么我的代码没有正确更新我的 TreeView 节点加法或减法。 对于有点大的代码转储,我提前道歉,但我觉得说明问题很重要。

对于初学者,我的可观察对象类

public abstract class ObservableObject : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    [NotifyPropertyChangedInvocator]
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

树节点基类

public abstract class TreeNodeBase : ObservableObject
{
    protected const string ChildNodesPropertyName = "ChildNodes";
    protected string name;
    public string Name
    {
        get
        {
            return this.name;
        }
        set
        {
            this.name = value;
            this.OnPropertyChanged();
        }
    }
    protected IList<TreeNode> childNodes;
    protected TreeNodeBase(string name)
    {
        this.Name = name;
        this.childNodes = new List<TreeNode>();
    }
    public IEnumerable<TreeNode> ChildNodes
    {
        get
        {
            return this.childNodes;
        }
    }
    public TreeNodeBase AddChildNode(string name)
    {
        var treeNode = new TreeNode(this, name);
        this.childNodes.Add(treeNode);
        this.OnPropertyChanged(ChildNodesPropertyName);
        return treeNode;
    }
    public TreeNode RemoveChildNode(string name)
    {
        var nodeToRemove = this.childNodes.FirstOrDefault(node => node.Name.Equals(name));
        if (nodeToRemove != null)
        {
            this.childNodes.Remove(nodeToRemove);
            this.OnPropertyChanged(ChildNodesPropertyName);
        }
        return nodeToRemove;
    }
}
public class TreeNode : TreeNodeBase
{
    public TreeNodeBase Parent { get; protected set; }
    public TreeNode(TreeNodeBase parent, string name)
        : base(name)
    {
        this.Parent = parent;
    }
}

TreeNodeRoot 类

public class TreeViewRoot : TreeNodeBase
{
    public TreeViewRoot(string name)
        : base(name)
    {
    }
}

树节点类

public class TreeNode : TreeNodeBase
{
    public TreeNodeBase Parent { get; protected set; }
    public TreeNode(TreeNodeBase parent, string name)
        : base(name)
    {
        this.Parent = parent;
    }
}

树视图用户控件 Xaml

<UserControl x:Class="TreeViewExperiment.TreeView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:treeViewExperiment="clr-namespace:TreeViewExperiment"
             xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="400"
             d:DataContext="{d:DesignInstance treeViewExperiment:TreeViewmodel}">
    <UserControl.DataContext>
        <treeViewExperiment:TreeViewmodel/>
    </UserControl.DataContext>
    <Grid Background="White">
        <Grid.Resources>
            <HierarchicalDataTemplate x:Key="TreeViewHierarchicalTemplate" ItemsSource="{Binding ChildNodes}">
                <TextBlock Text="{Binding Name}"/>
            </HierarchicalDataTemplate>
            <Style TargetType="Button">
                <Setter Property="FontFamily" Value="Verdana"/>
                <Setter Property="FontWeight" Value="Bold"/>
            </Style>
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition Height="6*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TreeView Grid.Row="0" x:Name="Tree" ItemsSource="{Binding RootLevelNodes}" ItemTemplate="{StaticResource TreeViewHierarchicalTemplate}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectedItemChanged">
                    <i:InvokeCommandAction
                        Command="{Binding SetSelectedNode}"
                        CommandParameter="{Binding SelectedItem, ElementName=Tree}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </TreeView>
        <Grid Grid.Row="1" Height="25">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="4*"/>
                <ColumnDefinition Width="2*"/>
                <ColumnDefinition Width="2*"/>
            </Grid.ColumnDefinitions>
            <TextBox x:Name="NameTextBox" Grid.Column="0" VerticalAlignment="Center" FontFamily="Verdana"/>
            <Button Grid.Column="1" Content="Add Node" Command="{Binding AddNode}" CommandParameter="{Binding Text, ElementName=NameTextBox}" Background="Green"/>
            <Button Grid.Column="2" Content="Remove Node" Command="{Binding RemoveNode}" Background="Red"/>
        </Grid>
    </Grid>
</UserControl>

最后是树视图模型

public class TreeViewmodel : ObservableObject
{
    public ICommand SetSelectedNode { get; private set; }
    public ICommand AddNode { get; private set; }
    public ICommand RemoveNode { get; private set; }
    public TreeViewmodel()
    {
        this.SetSelectedNode = new ParamaterizedDelegateCommand(
            node =>
                {
                    this.SelectedTreeNode = (TreeNodeBase)node;
                });
        this.AddNode = new ParamaterizedDelegateCommand(name => this.SelectedTreeNode.AddChildNode((string)name));
        this.RemoveNode = new DelegateCommand(
            () =>
                {
                    if (selectedTreeNode.GetType() == typeof(TreeNode))
                    {
                        var parent = ((TreeNode)this.SelectedTreeNode).Parent;
                        parent.RemoveChildNode(this.SelectedTreeNode.Name);
                        this.SelectedTreeNode = parent;
                    }
                });
        var adam = new TreeViewRoot("Adam");
        var steve = adam.AddChildNode("Steve");
        steve.AddChildNode("Jack");
        this.rootLevelNodes = new List<TreeViewRoot> { adam, new TreeViewRoot("Eve") };
    }
    private TreeNodeBase selectedTreeNode;
    private readonly IList<TreeViewRoot> rootLevelNodes;
    public IEnumerable<TreeViewRoot> RootLevelNodes
    {
        get
        {
            return this.rootLevelNodes;
        }
    }
    public TreeNodeBase SelectedTreeNode
    {
        get
        {
            return this.selectedTreeNode;
        }
        set
        {
            this.selectedTreeNode = value;
            this.OnPropertyChanged();
        }
    }
}

所以我知道当添加子元素被删除时,应该通知 UI,因为当我调试它时,我可以看到在这两种情况下都调用了 ChildNode 属性上的 get 访问器,但 UI 上显示的内容保持不变。

过去我已经解决了这个问题,但是使用ObservableCollections,这似乎是StackOverflow上此类问题的大多数解决方案所指向的,但是为什么这个解决方案不起作用? 我错过了什么?

使用 HierarchicalDataTemplate 的 WPF MVVM 树视图未更新

问题是你滥用了INotifyPropertyChanged。在您的代码中,您正在通知视图您的属性ChildNodes更改,但事实并非如此,因为TreeViewItem.ItemsSource仍然等于您的ChildNodes属性。

INotifyPropertyChanged视图模型中的基础集合对象更改时,将导致 UI 更新。

要在集合中出现新项目时更新ItemsSource,您需要使用实现INotifyCollectionChanged的集合。

正如MSDN所说:

可以枚举实现 IEnumerable 接口的任何集合。但是,若要设置动态绑定,以便集合中的插入或删除操作自动更新 UI,集合必须实现 INotifyCollectionChanged 接口。此接口公开一个事件,每当基础集合发生更改时,都应引发该事件。

这就是为什么SO上的每个人都建议使用ObservableCollection

编辑:

如果要公开只读集合,则应选中ReadOnlyObservableCollection<T>类。它可以作为可以非公开的ObservableCollection的包装器。