Initialize a collection with a type from another collection

时间:2015-11-12 12:10:04

标签: c# wpf

This might and impossible scenario and I may be trying to do something that I should not be doing in the first place but here it is.

  • I have a custom WPF Control which has two IEnumerable collections
  • The first collection (ItemsSource) is declared via the XAML and might be of any type of objects.
  • The second collection the one that I am implementing is again an IEnumerable which I want to initialize as ObservableCollection.
  • Here is my issue as I am restricted that both the collections are of the same type of objects (no I cannot use object as a type). For example the ItemsSource is of "MyItem" type objects and I want to initialize the second collection to be ObservableCollection().

Is this possible? Am i doing something that I should not be doing? Any hints will appreciated. On a side note if I pass the second collection via the XAML all is well, but I do not want to add such restriction to the feature I am implementing.

Edit:

Here are some code snippets to showcase the scenario: The first collection, note that this collection is inherited from the System.Windows.Controls.ItemsControl class:

public IEnumerable ItemsSource { get; set; }

The second collection:

public IEnumerable SelectedItems
{
    get
    {
        this.InitializeSelectedItemsCollectionIfRequired();
        return (IEnumerable)GetValue(SelectedItemsProperty);
    }
    set
    {
        SetValue(SelectedItemsProperty, value);
    }
}

private void InitializeSelectedItemsCollectionIfRequired()
{
    if (this.GetValue(SelectedItemsProperty) == null)
    {
        // Here is where I want to initialize the second collection if it was not already set in via a Binding in the XAML
        this.SelectedItems = new System.Collections.ObjectModel.ObservableCollection<"dont know how to pass correct type here">();
    }
}

1 个答案:

答案 0 :(得分:1)

由于您不知道确切的类型,因此您可以简单地恢复为最基本的类型object

this.SelectedItems = new System.Collections.ObjectModel.ObservableCollection<object>();