PigSpider
PigSpider

Reputation: 1011

WPF binding to Dictionary of <type,Object> 's Object.Property

I want to have a combobox' source binding to a specific key's Oject.Name field. The only examples I can find are for Dictionaries of strings.

Here is what I have tried:

    public class XMLTypeData
{
    public string Abbreviation;
    public string Name;
    public string Value;
    public Dictionary<string, XMLTypeData> Children = new Dictionary<string, XMLTypeData>();
}

I have previously loaded values into the dictionary:

Dictionary<Type, List<XMLTypeData>> XML = new Dictionary<Type, List<XMLTypeData>>();

I am not sure if this is possible

 <ComboBox x:Name="CBType" DisplayMemberPath="Key" SelectedValuePath="Value.Name" ItemsSource="{Binding XML}"  Text="{Binding Source={StaticResource UserControlBindings},Path=SelectedTreeEntity.Type/>

Upvotes: 1

Views: 621

Answers (1)

PigSpider
PigSpider

Reputation: 1011

Thanks to Fabulous I was able to achieve this. The problem was that I made a dictionary of a list. I changed the Dictionary as the following:

Dictionary<Type, XMLTypeData> XML = new Dictionary<Type, XMLTypeData>();

And I changed the DisplayMemberPath & SelectedValuePath properties in my XAML as the following:

<ComboBox x:Name="CBType" DisplayMemberPath="Key" SelectedValuePath="Value" ItemsSource="{Binding XML}"  Text="{Binding Source={StaticResource UserControlBindings},Path=SelectedTreeEntity.Type/>

Also to note, I set the itemsource of the combobox to the relevant children dictionary of the hierarchy:

CBType.ItemsSource = ElementaryTypes[SelectedType].Children;

And to set another combobox, which is dependant on the upper level on the hierarchy:

private void CBType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if(CBType.SelectedItem is KeyValuePair<string,XMLTypeData> KeyPair)
            {
             if (ElementaryTypes[SelectedType].Children.Keys.Contains(KeyPair.Key))
                 {
                CBSubType.ItemsSource = ElementaryTypes[SelectedType].Children[KeyPair.Key].Children;
                 }
            }
    }

Upvotes: 1

Related Questions