WPF TreeView ObservableCollection通知示例代码

时间:2014-06-18 19:18:40

标签: c# wpf treeview observablecollection

我正在尝试编写一个C#WPF应用程序,但我仍然坚持使用TreeView和ObservableCollection。

这是我的TreeView项目。

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

我从其他窗口修改了这些项目,我需要更新此树视图而不重新加载所有项目。我进行了搜索,发现了ObservableCollection。但我无法理解如何使用ObservableCollection并通知更改并更新此列表。 你能给我一些示例代码或帮我做这件事吗?

1 个答案:

答案 0 :(得分:1)

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

这只是另一个样本,

你的模特:

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

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

在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