0

Based on this answer https://stackoverflow.com/a/33109026/426386 I add an empty Item to my ComboBox collection. As my Combobox has a SelectedValue and SelectedValuePath defined, I'll run into Bindingerrors:

    <UserControl.Resources>
        <ObjectDataProvider
            x:Key="CardTypeProvider"
            MethodName="GetLocalizedEnumValues"
            ObjectType="{x:Type base:Localize}">
            <ObjectDataProvider.MethodParameters>
                <x:Type
                    TypeName="base:CardTypes" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </UserControl.Resources>

    <ComboBox           
        DisplayMemberPath="Value"
        SelectedValue="{Binding GroupByCardType, UpdateSourceTrigger=PropertyChanged}"
        SelectedValuePath="Key">
        <ComboBox.Resources>
            <CollectionViewSource
                x:Key="Items"
                Source="{Binding Source={StaticResource CardTypeProvider}}" />
        </ComboBox.Resources>
        <ComboBox.ItemsSource>
            <CompositeCollection>
                <TextBlock />
                <CollectionContainer
                    Collection="{Binding Source={StaticResource Items}}" />
            </CompositeCollection>
        </ComboBox.ItemsSource>
    </ComboBox>

The ObjectDataProvider returns following Type:

Dictionary<Enum, string>

To avoid the Binding errors I want to instantiate a KeyValuePair<Enum, string> instead of the TextBlock. Possible somehow?

Community
  • 1
  • 1
Florian
  • 380
  • 3
  • 20

1 Answers1

0

I am afraid you can't create instances of generic types in XAML and you can't create a type that derives from the value type KeyValuePair<TKey, TValue> either but you could create another type that has Key and Value properties and add an instance of this one to the CompositeCollection:

public class EmptyItem
{
    public YourEnum Key { get; set; }
    public string Value { get; set; } = "(Select)";
}

This should satisfy the binding issue.

The other option would be to programmatically add an actual KeyValuePair<TKey, TValue> to the collection, e.g.:

CompositeCollection cc = comboBox.ItemsSource as CompositeCollection;
cc.Insert(0, new KeyValuePair<YourEnum, string>(..., "..."));
mm8
  • 163,881
  • 10
  • 57
  • 88
  • According to http://stackoverflow.com/a/1708753/426386 I'm able to model a generic type, but am I able to instantiate it? Or asking more simplified: can I create instances of types (or wrap it somehow)? – Florian Dec 16 '16 at 13:15
  • You cannot create instances of g e n e r i c types in XAML. You could define a non-generic class that wraps the KeyValuePair class or you could just add a Key and Value property to it as per my answer. All elements are instances of some type. – mm8 Dec 16 '16 at 13:20