如何在Wpf c#</class> </object>中将类型从ObservableCollection <object>更改为ObservableCollection <class>

时间:2014-10-22 09:18:17

标签: c#

我想创建用于生成要在treeview中显示的数据的函数。 但是下面的代码有问题,请帮助我。

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

show Tree View的类

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

1 个答案:

答案 0 :(得分:0)

你不能。想象一下,你有这个方法:

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
}