[英]Bind Dictionary to ItemsControl in C#/WPF
I'm trying to bind KeyValuePair Elements from a Dictionary to a ItemsControl.我正在尝试将字典中的 KeyValuePair 元素绑定到 ItemsControl。 My Dictionary has 15 Elements and the following code shows me 15 TextBoxes:
我的词典有 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>
Unfortunately without any TextBox content (which would be Key or Value).不幸的是,没有任何 TextBox 内容(可能是键或值)。 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. 如果我能正确理解您的XAML,则字典中的每个对象都有一个您试图绑定到的名为“文本”的字段。 If so and you make the above changes, you will need to change your DataTemplate as well:
如果是这样,并且您进行了上述更改,则还需要更改您的DataTemplate:
<TextBox Text="{Binding Text}" />
See this article for more info. 有关更多信息,请参见本文 。 HTH.
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. http://www.dev102.com/2008/03/07/binding-a-wpf-control-to-a-dictionary/上的代码似乎无效。
Let us say you have a Dictionary called RowValues, with both the [key, value] defined as [string, string]. 假设您有一个名为RowValues的字典,其中[key,value]都定义为[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}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.