Álvaro García
Álvaro García

Reputation: 19356

observableCollection: how to establish type in runtime?

I have a dataGrid, that uses an observableCollection to bind the ItemsSource property (MVVM pattern). So in my viewmodel I have a property that is an observableCollection (myCollection). However, this dataGrid can show information of two different types, that their are decide in runtime.

Normally, I use the the observableCollection in this away:

ObservableCollection<myType> myCollection = new ObservableCollection<myType>();

But now, I have a string as parameter that say me what type I need, so I would like to do something like that:

if(parameter == "TypeA")
{
    myCollection = new ObservableCollection<TypeA>();
}

if(parameter == "TypeB")
{
    myCollection = new ObservableCollection<TypeB>();
}

is it possible to do that?

Upvotes: 0

Views: 489

Answers (2)

B.Balamanigandan
B.Balamanigandan

Reputation: 4875

Just Use the dynamic Keyword instead of Exact Type for Declaring ObservableCollection in Runtime

private ObservableCollection<dynamic> DynamicObservable(IEnumerable source)
    {

        ObservableCollection<dynamic> SourceCollection = new ObservableCollection<dynamic>();

        SourceCollection.Add(new MobileModelInfo { Name = "iPhone 4", Catagory = "Smart Phone", Year = "2011" });

        SourceCollection.Add(new MobileModelInfo { Name = "S6", Catagory = "Ultra Smart Phone", Year = "2015" });

        return SourceCollection;

    }

public class MobileModelInfo
{
    public string Name { get; set; }
    public string Catagory { get; set; }
    public string Year { get; set; }
}

Upvotes: 0

dowhilefor
dowhilefor

Reputation: 11051

If you make TypeA and TypeB derived from a common base class or interface, you can keep the same collection.

But if you want two different collections, you you can raise the collection property to notify about the changed type.

IEnumerable MyCollection
{
    get
    {
        if(CurrentType == typeof(TypeB)
            return myTypeBCollection;
        else if(CurrentType == typeof(TypeA)
            return myTypeACollection;
    }
}

So your bind MyCollection in your view to ItemsSource, and raise that the property has changed.

Remember that you might need a different DataTemplate, where a DataTemplateSelector might come in handy.

Upvotes: 1

Related Questions