Mar
7th | 2008

Binding a WPF Control To a Dictionary

Filed under .Net, C#, WPF | Posted by Amit

WPF Combobox BindingBinding to a dictionary can be tricky.

It sounds simple but it never works on the first try. Usually when you first run you application you see that instead of the beautiful template you created for the items, you get something that looks like a pair of key and value. your binding works fine, you just did not think about what are you binding to. every item in a dictionary is a pair (Key,Value) and that is exactly what you get as the binded item. You have two ways of handle this, You can either change the markup of the Binding expression to include the reference to the Value :

<ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation=”Horizontal”>
                        <TextBlock Text=”{Binding Value.Text}”></TextBlock>
                        <TextBlock> = </TextBlock>
                        <TextBlock Text=”{Binding Value.Value}”></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>

or you can change the binding expression of the control to refer to the Values property of the dictionary:

<ComboBox Height=”23″ Margin=”0,14,9,0″ Name=”comboBox1″
                  VerticalAlignment=”Top” SelectedValuePath=”Key”
                  ItemsSource=”{Binding Items.Values}”
                  HorizontalAlignment=”Right” Width=”120″>

Now you have your control binded to a Dictionary, Hurray!

Subscribe to our feed and get the complete code sample for this article

Enjoy

Amit.

Tags: , , , , , ,

3 Responses to “Binding a WPF Control To a Dictionary”



  1. By Martin Cook on Jun 19, 2008 | Reply

    Nice one, thanks! The top one worked for me, but not the second one. Perhaps because it should be ItemsSource=”{Binding Items.Value}” instead of ItemsSource=”{Binding Items.Values}” but I’d changed my code to use the first method before spotting that might be the case.

    Thanks again!
    Martin

  2. By Martin Cook on Jun 19, 2008 | Reply

    Upon further experimentation this is how I got the first example to work: -

    XAML:

    C#:
    Dictionary indexedObjects = new Dictionary();
    vehicleList.DataContext = indexedObjects.Values;

    Cheers,
    Martin

  3. By Martin Cook on Jun 19, 2008 | Reply

    Heh, cant post XAML then.

    Ah well.

Post a Comment

Search Dev102