如何从ObservableCollection<;对象>;到ObservableCollection<;类&

本文关键字:ObservableCollection lt gt 对象 | 更新日期: 2023-09-27 18:27:21

我想创建一个函数来生成要在树视图中显示的数据。但是下面的代码有一些问题,请帮助我。

//Class for hold all data
public class DataControl
{
    public string Type { get; set; }
    public ObservableCollection<object> Data;
    //constructor
    public DataControl(string type, ObservableCollection<object> data)
    {
        Type = type;
        Data = data;
    }
}

类数据模型====================================

public class MyData
{
    public string Id { get; set; }
    public string Name { get; set; }
}

显示树状视图的类

public class ShowTreeView
{
    public ObservableCollection<DataControl> DataStore { get; set; }
    public ObservableCollection<MyData> Data { get; set; }
    //Function Show Data In Tree View
    public void ShowData()
    {
        for (int i = 0; i <= 5; i++)
        {
            var obj = new MyData { Id = "0", Name = "Name1" };
            Data.Add(obj);
            //How do i can convert type from ObservableCollection<object> to
            //ObservableCollection<MyData>
            //Please help me.
            // Thank you very much.
            var tree= new DataControl(i.ToString(), Data); //Error code.
            DataStore.Add(tree);
        }
    }
}

不管怎样,我想问,如何在MVVM的TreeView控件中创建动态函数来显示数据?

提前感谢:D

如何从ObservableCollection<;对象>;到ObservableCollection<;类&

你不能。想象一下你有这样的方法:

void foo(ObservableCollection<object> collection) {
    collection.Add(new Tiger());
}

在这种情况下调用:

var ints = new ObservableCollection<int>();
foo(ints);

可以想象,它是无效的(您正试图将类型为Tiger的对象添加到Int32的集合中)。您可以做的是将foo()更改为接受使集合可观察:INotifyCollectionChanged的接口。然后你的课程将变成:

public class DataControl {
    public string Type { get; set; }
    public INotifyCollectionChanged Data;
    public DataControl(string type, INotifyCollectionChanged data) {
        Type = type;
        Data = data;
    }
}

如果(万一)您需要在DataControl中修改您的集合,您可以简单地将其转换为正确的类型(但IMO这将违反DataControl合同)。想象一下,你正在观察这样的收集,你有一个处理程序:

void OnObservedCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) {
    if (e.Action == NotifyCollectionChangedAction.Add)
        AddNewItemsToTreeView(e.NewItems); // NewItems are all "untyped" object
}