I'm working on a problem where I have two nested TabControls. Both should bind to a collection. The parent tab control should bind to a collection called devices. This devices-collection should contain several ObservableCollections of different types which should be displayed in a different way in the ContentTemplate.
I tried something like this:
public ObservableCollection<CellPhone> CellPhones { get; set; }
public ObservableCollection<Watch> Watches { get; set; }
public ObservableCollection<ObservableCollection<DeviceItem>> Devices { get; set; }
Watch
and CellPhone
inherit from DeviceItem
.
I tried the following:
CellPhones = new ObservableCollection<CellPhone>();
Watches = new ObservableCollection<Watch>();
Devices = new ObservableCollection<ObservableCollection<DeviceItem>>();
Devices.Add(CellPhones); // it fails here...
It says:
cannot convert from 'System.Collections.ObjectModel.ObservableCollection<CellPhone>' to 'System.Collections.ObjectModel.ObservableCollection<DeviceItem>'
I do understand this error message, but I haven't found a workaround.
I read about covariance in c#, but apparently that's not working for ObservableCollections.
Do you have another idea on how to solve this?
I created a separate class Device
public class Device
{
public Device(String arg_DeviceName)
{
DeviceName = arg_DeviceName;
}
public String DeviceName { get; }
public ObservableCollection<DeviceItem> Items
{
get; set;
}
}
And than I solved it like this:
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);
With this I can bind to the Items
-Property of the Device
-class.
Thank you HimBromBeere. You opened my eyes and pushed me towards the solution.