0

我有一个 TreeView 控件,其 ItemSource 绑定到字符串集合。如果我像这样将项目添加到集合中

private void AddItems()
{
    _myList.Add("string1");
    _myList.Add("string2");
    _myList.Add("string3");
    NotifyOfPropertyChanged(() => MyList);
}

我的字符串集合是这样定义的

private Collection<string> _myList;
public Collection<string> MyList 
{ 
    get 
    { 
        return _myList;
    }
}

然后在 treeView 控件上没有任何更新。但是,如果我这样定义 Collection

 private Collection<string> _myList;
    public Collection<string> MyList 
    { 
        get 
        { 
            _myList = new Collection<string>();
            _myList.Add("string1");
            _myList.Add("string2");
            _myList.Add("string3");
            return _myList;
        }
        set { _myList = value; NotifyOfPropertyChange(() => MyList); }
    }

并像这样设置集合

 private void AddItems()
    {
        Collection<string> tempList = new Collection<string>();
        tempList.Add("string1");
        tempList.Add("string2");
        tempList.Add("string3");
        MyList = tempList;
    }

然后树控件确实显示了这些项目。

4

2 回答 2

1

您的初始代码AddItems永远不会更改作为MyList对列表对象的引用的属性的值,它只是在内部更改引用的实例。

如果要更改集合,请使用该INotifyCollectionChanged界面。

于 2013-09-09T09:43:56.417 回答
1

最有可能的原因是该列表仍然是相同的参考。你真正想要的是一个ObservableCollection<T>.

于 2013-09-09T09:43:17.133 回答