简体   繁体   中英

WPF treeview with HierarchicalDataTemplate shows only 1 item

I am trying to bind to a WPF treeview but I am getting unexpected results. I bind to my viewmodel which appears to work as I get a single item but it does not allow me to expand to child items. I cant see what I'm doing wrong. Does anyone have any ideas?

I have the following model

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

I have the following view model

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

My Xaml looks like

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

Its ok I found it. I needed to add a Items source value to the HierarchicalDataTemplate of Subitems

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM