Monday, February 21, 2011

Bind Dictionary to ItemsControl in C#/WPF

Hello,

I'm trying to bind KeyValuePair Elements from a Dictionary to a ItemsControl. My Dictionary has 15 Elements and the following code shows me 15 TextBoxes:

    <WrapPanel Name="PersonsWrapPanel" Grid.Row="0">
            <ItemsControl ItemsSource="{Binding Persons}" >
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel Orientation="Horizontal" Width="auto">
                        </WrapPanel>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                            <TextBox Text="{Binding Value.Text}"></TextBox>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </WrapPanel>

Unfortunately without any TextBox content (which would be Key or Value). Any ideas?

Thanks for any help!

Cheers

From stackoverflow
  • Perhaps try binding directly to the values of the dictionary:

    ItemsSource="{Binding Persons.Values}"
    

    If I am understanding your XAML properly, each object in the dictionary has a field called "Text" to which you are trying to bind. If so and you make the above changes, you will need to change your DataTemplate as well:

    <TextBox Text="{Binding Text}" />
    

    See this article for more info. HTH.

  • I solved it by using this line:

      <TextBox Text="{Binding Value, Mode=OneWay}"></TextBox>
    

    The code on http://www.dev102.com/2008/03/07/binding-a-wpf-control-to-a-dictionary/ doesn't seem to work.

    Thanks for the answer Malcolm!

    Cheers

0 comments:

Post a Comment