不同类型的 ObservableCollection 集合

Collection of ObservableCollections of different types

我正在解决我有两个嵌套 TabControl 的问题。两者都应该绑定到一个集合。 父选项卡控件应绑定到名为设备的集合。 此设备集合应包含多个不同类型的 ObservableCollection,它们应以不同的方式显示在 ContentTemplate 中。

我试过这样的事情:

public ObservableCollection<CellPhone> CellPhones { get; set; }

public ObservableCollection<Watch> Watches { get; set; }

public ObservableCollection<ObservableCollection<DeviceItem>> Devices { get; set; }

WatchCellPhone 继承自 DeviceItem

我尝试了以下方法:

CellPhones = new ObservableCollection<CellPhone>();
Watches = new ObservableCollection<Watch>();
Devices = new ObservableCollection<ObservableCollection<DeviceItem>>();
Devices.Add(CellPhones); // it fails here...

它说:

cannot convert from 'System.Collections.ObjectModel.ObservableCollection<CellPhone>' to 'System.Collections.ObjectModel.ObservableCollection<DeviceItem>'

我理解这个错误消息,但我还没有找到解决方法。

我阅读了有关 c# 中的协方差的信息,但显然这不适用于 ObservableCollections。

您对如何解决这个问题有其他想法吗?

A List<Derived> 根本就不是 List<Base>,即使 DerivedBase。这同样适用于 ObservableCollection。换句话说:如果允许这样做,您可以同时将 List<CellPhone>List<Watch> 放入您的列表中。任何用户怎么知道他的列表中实际有哪些项目:

var a = Devices[0]; // what type has a here? compiler can´t infer that type

为什么不直接将 WatchesCellPhones 设为 ObservableCollection<DeviceItem>

public ObservableCollection<DeviceItem> CellPhones { get; set; }    
public ObservableCollection<DeviceItem> Watches { get; set; }    
public ObservableCollection<ObservableCollection<DeviceItem>> Devices { get; set; }

现在您可以轻松做到这一点:

Devices.Add(CellPhones);
Devices.Add(Watches);

我创建了一个单独的 class Device

public class Device
{

    public Device(String arg_DeviceName)
    {
        DeviceName = arg_DeviceName;
    }


    public String DeviceName { get; }

    public ObservableCollection<DeviceItem> Items
    {
        get; set;
    }
}

我是这样解决的:

public Device CellPhones{ get; set; }

public ObservableCollection<DeviceItem> CellPhoneItems
{
    get; set;
}

public Device Watches { get; set; }

public ObservableCollection<DeviceItem> WatchItems
{
    get; set;
}

public ObservableCollection<Device> Devices
{
    get; set;
}



CellPhones = new Device("Cells");
CellPhoneItems = new ObservableCollection<DeviceItem>();
Watches = new Device("Watch");
WatchItems = new ObservableCollection<DeviceItem>();
CellPhones.Items = CellPhoneItems;
Watches.Items = WatchItems;
Devices = new ObservableCollection<Device>();
Devices.Add(CellPhones);
Devices.Add(Watches);

有了这个,我可以绑定到 Device-class 的 Items-属性。

谢谢 HimBromBeere。你睁开了我的眼睛,把我推向了解决方案。

我在 Xamarin.Forms 中所做的是使用接口。

因此,成像我有一个名为 Student 的 class 和一个名为 Teacher 的 class。

我知道它们都有一些共同的属性,例如 DateOfBirth 所以我有一个名为:ISchoolMember 的接口具有:

DateTime? DateOfBirth {get; set;}

如果 StudentTeacher 都实现了我的 ISchoolMember 接口,我现在可以创建一个 ObservableCollection(或者更好,ObservableRangeCollection)类型ISchoolMember 所以通过这种方式我可以拥有 StudentTeacher 或任何其他在其中实现我的接口的类型。

当我只需要学生时,我可以在 LINQ 查询中使用 OfType<Student>()