WPF TreeView ObservableCollection通知样例代码

本文关键字:样例 代码 通知 ObservableCollection TreeView WPF | 更新日期: 2023-09-27 18:09:27

我正试图写一个c# WPF应用程序,我被困在TreeView和ObservableCollection。

这是我的TreeView项目。

| Root
--- SubItem
------ SubItem
| Root
--- SubItem
------ SubItem
---------- SubItem

我正在修改这个项目从其他窗口,我需要更新这个树视图没有重新加载所有项目。我搜索了一下,找到了ObservableCollection。但我不明白如何使用ObservableCollection和通知的变化和更新这个列表。你能给我一些示例代码或帮助我这样做吗?

WPF TreeView ObservableCollection通知样例代码

这是一个实现Simplifying the WPF TreeView by Using the ViewModel Pattern的好例子。

这只是另一个例子,

你的模型:

public interface IFolder
{
    string FullPath { get; }
    string FolderLabel { get; }
    ObservableCollection<IFolder> Folders { get; } 
}

你的视图模型:

class ViewModel : INotifyPropertyChanged 
{
    public ViewModel()
    {
        m_folders = new ObservableCollection<IFolder>();
        //add Root items
        Folders.Add(new Folder { FolderLabel = "Dummy1", FullPath = @"C:'dummy1" });
        Folders.Add(new Folder { FolderLabel = "Dummy2", FullPath = @"C:'dummy2" });
        Folders.Add(new Folder { FolderLabel = "Dummy3", FullPath = @"C:'dummy3" });
        Folders.Add(new Folder { FolderLabel = "Dummy4", FullPath = @"C:'dummy4" });
        //add sub items
        Folders[0].Folders.Add(new Folder { FolderLabel = "Dummy11", FullPath = @"C:'dummy11" });
        Folders[0].Folders.Add(new Folder { FolderLabel = "Dummy12", FullPath = @"C:'dummy12" });
        Folders[0].Folders.Add(new Folder { FolderLabel = "Dummy13", FullPath = @"C:'dummy13" });
        Folders[0].Folders.Add(new Folder { FolderLabel = "Dummy14", FullPath = @"C:'dummy14" });
    }
    public string TEST { get; set; }

    private ObservableCollection<IFolder> m_folders;
    public ObservableCollection<IFolder> Folders
    {
        get { return m_folders; }
        set
        {
            m_folders = value;
            NotifiyPropertyChanged("Folders");
        }
    }
    void NotifiyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(property));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}
在xaml:

      <TextBlock Text="Simple root binding" Foreground="Red" Margin="10,10,0,0" />
        <TreeView ItemsSource="{Binding Folders}" Margin="10">
            <TreeView.ItemTemplate>
                <DataTemplate>
                    <TreeViewItem Header="{Binding FolderLabel}"/>
                </DataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>

Full code