Wpf:我如何知道TreeView是否已更新?

时间:2010-01-20 09:03:51

标签: c# wpf events treeview

我正在使用Wpf TreeView,在此我可以动态添加TreeViewItems。 有没有办法知道树何时更新?我尝试使用TreeView绑定的ObservableCollection的CollectionChanged事件但是没有用。

编辑:

我的代码是这样的:

class Temp
{
    public void Load()
    {
        DeriveA d1 = new DeriveA();
        DeriveB d2 = new DeriveB();
        DeriveB d3 = new DeriveB();
        DeriveC d4 = new DeriveC();
        DeriveC d5 = new DeriveC();
        d1.Items.Add(d2);
        d1.Items.Add(d3);
        d2.Items.Add(d4);
        d2.Items.Add(d5);

        List = new ObservableCollection<object>();
        List.Add(d1);
        tree.ItemsSource = List;

        DeriveC d6 = new DeriveC();
        d3.Items.Add(d6);        //At this point, I want to know that List got updated
    }

    public ObservableCollection<object> List
    {
        get;
        set;
    }
}

class Base
{
    ObservableCollection<Base> Items = new ObservableCollection<Base>();
}

class DeriveA : Base
{
}

class DeriveB : Base
{
}

class DeriveC : Base
{
}

如何在任何级别更新List属性?

2 个答案:

答案 0 :(得分:1)

SourceUpdated事件怎么样?


修改 SourceUpdated事件没有触发,但我尝试使用ObservableCollection.CollectionChanged并且它没问题,所以我会要求给你一些代码,这是我测试过的,希望它有所帮助:

public partial class Window1 : Window
{
    ObservableCollection<string> items = new ObservableCollection<string>()
    {
        "string1","string2","string3","string4","string5"
    };
    public Window1()
    {
        InitializeComponent();
        DataContext = this;
        tree.ItemsSource = items;
        items.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(items_CollectionChanged);
    }

    void items_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        MessageBox.Show("Event raised");
    }


    private void btnAddItem_Click(object sender, RoutedEventArgs e)
    {
        items.Add("string6");
    }
}

和xaml

<StackPanel Orientation="Vertical">
            <TreeView x:Name="tree" />
            <Button x:Name="btnAddItem" Click="btnAddItem_Click" Content="AddItem" />
</StackPanel>

答案 1 :(得分:0)

你可以这样:

private void Loaded()
{
    MyTreeNode d1 = new MyTreeNode();
    MyTreeNode d2 = new MyTreeNode();
    MyTreeNode d3 = new MyTreeNode();
    MyTreeNode d4 = new MyTreeNode();
    MyTreeNode d5 = new MyTreeNode();
    d1.AddNode(d2);
    d1.AddNode(d3);
    d2.AddNode(d4);
    d2.AddNode(d5);

    d1.CollectionChanged += (s, e) =>
    {
        MessageBox.Show("Tree Changed");
    };

    MyTreeNode d6 = new MyTreeNode();
    d3.AddNode(d6);
}  

public class MyTreeNode : ObservableCollection<MyTreeNode>
{
    public void AddNode(MyTreeNode node)
    {
        this.Add(node);
        node.CollectionChanged += (s, e) => this.OnCollectionChanged(e);
    }
}