klashagelqvist
klashagelqvist

Reputation: 1261

Generic list conversion

I have three classes

public class OSiteEquipment : IPlantItem
public class OSiteSubSystem : IPlantItem
public class OSiteComponent : IPlantItem

Each implement interface IPlantItem

In my xaml i bind to an Observable collection like

public ObservableCollection<IPlantItem> CurrentItems

Sometimes i need to bind CurrentItems to an collection of OSiteEquipments and sometimes to OSiteSubSystem

If i try to set CurrentItems when i load the view like this

CurrentItems = this.siteDocument.Sitestructure.Equipments;

Where Sitestructure.Equipments is an observable collection of OSiteEquipment, compiler says i cant convert from Observablecollection<IPlantItem> to Observablecollection<OSiteEquipment>

Is there a way to solve this. DO i need to make an explicit conversion

EDIT

Solved it , instead of defining CurrentItems as ObservableCollection i as

object CurrentItems

The reason i didnt do it in the beginning was that i thougt i would destroy the notification binding, but it still works fine.

Upvotes: 2

Views: 164

Answers (1)

svick
svick

Reputation: 244777

Explicit conversion from ObservableCollection<OSiteEquipment> to Observablecollection<IPlantItem> wouldn't work either. If you wanted this to work, you would need to copy the elements of the OSiteEquipment collection to a new IPlantItem. But then changes to the original collection wouldn't affect the new collection, so this is not what you want.

You already found a solution, but I think it would be better if you changed the type of CurrentItems to IEnumerable<IPlantItem>. This shouldn't affect the binding, but it means your code is safer and more self-documenting (it's more obvious what should that property be).

Upvotes: 2

Related Questions