在C#/ WPF中将Dictionary绑定到ItemsControl

时间:2009-07-08 12:46:06

标签: c# wpf dictionary itemscontrol

我正在尝试将KeyValuePair元素从Dictionary绑定到ItemsControl。 我的词典有15个元素,下面的代码显示了15个文本框:

<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>

不幸的是没有任何TextBox内容(可能是Key或Value)。 有什么想法吗?

3 个答案:

答案 0 :(得分:4)

也许尝试直接绑定到字典的值:

ItemsSource="{Binding Persons.Values}"

如果我正确理解您的XAML,字典中的每个对象都有一个名为“Text”的字段,您尝试绑定该字段。如果是,并且您进行了上述更改,则还需要更改DataTemplate:

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

有关详细信息,请参阅this article。 HTH。

答案 1 :(得分:3)

我用这条线解决了它:

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

http://www.dev102.com/2008/03/07/binding-a-wpf-control-to-a-dictionary/上的代码似乎不起作用。

答案 2 :(得分:0)

我们假设您有一个名为RowValues的词典,其中[key,value]定义为[string,string]。

现在要绑定到此词典的值对,您可以执行以下操作:

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

要显示文本(值),您可以绑定为:

<TextBlock Text="{Binding}"/>