WPF TreeView ObservableCollection notifying sample

2019-06-09 09:27发布

I'm trying to write a C# WPF application and I'm stuck with the TreeView and ObservableCollection.

This is my TreeView Items.

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

I'm modifyng this items from other window and I need to update this treeview without re-loading all items. I've made my search and I found ObservableCollection. But I can't understand how to use ObservableCollection and notify changes and update this list. Can you give me some sample code or help me with doing that?

1条回答
一夜七次
2楼-- · 2019-06-09 10:06

Here is a good example to Implement Simplifying the WPF TreeView by Using the ViewModel Pattern.

This is just another sample,

Your Model:

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

Your ViewModel:

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

In 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

查看更多
登录 后发表回答