带有HierarchicalDataTemplate的WPF树视图仅显示1个项目

问题描述 投票:0回答:1

我正在尝试绑定到WPF树视图,但是得到了意外的结果。我绑定到我的视图模型,该视图模型在我获得单个项目时似乎可以工作,但是它不允许我扩展到子项目。我看不到我在做什么错。有人有什么想法吗?

我有以下型号

public class Folder
{
    public string Name { get; set; }
    public IEnumerable<Folder> Subfolders { get; set; }
}

我有以下视图模型

    public class Vm : INotifyPropertyChanged
    {
        private IEnumerable<Folder> _items;

        public Vm()
        {
            var x = new List<Folder>();
            x.Add(new Folder()
            {
                Name = "Item1",
                Subfolders = new List<Folder>()
                {
                    new Folder()
                    {
                        Name = "SubItem1", Subfolders = new List<Folder>()
                        {
                            new Folder() { Name = "SubItem2", Subfolders = new List<Folder>()}
                        }
                    }
                }
            });

            Items = x;
        }

        public IEnumerable<Folder> Items
        {
            get => _items;
            set
            {
                _items = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

我的Xaml看起来像

<Window x:Class="WpfApp5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp5"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TreeView Height="450" Width="800" ItemsSource="{Binding Path=Items}">
            <TreeView.Resources>
                <HierarchicalDataTemplate DataType="{x:Type local:Folder}" >
                    <TextBlock Margin="5,0,0,0" FontWeight="Bold" Text="{Binding Name}"/>
                </HierarchicalDataTemplate>
            </TreeView.Resources>

        </TreeView>
    </Grid>
</Window>
wpf mvvm treeview
1个回答
0
投票

没关系,我找到了。我需要将“项目”源值添加到子项的HierarchicalDataTemplate

© www.soinside.com 2019 - 2024. All rights reserved.