简体   繁体   中英

Bind Dictionary to ItemsControl in C#/WPF

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?

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.

Let us say you have a Dictionary called RowValues, with both the [key, value] defined as [string, string].

Now to bind to the Value Pair of this dictionary, you can do the following:

<ItemsControl ItemsSource="{Binding RowValues.Values}" >

To display the text (Value), you can bind as:

<TextBlock Text="{Binding}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM