在 C#/WPF 中将字典绑定到 ItemsControl
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1097839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bind Dictionary to ItemsControl in C#/WPF
提问by Joseph jun. Melettukunnel
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:
我正在尝试将字典中的 KeyValuePair 元素绑定到 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>
Unfortunately without any TextBox content (which would be Key or Value). Any ideas?
不幸的是没有任何文本框内容(这将是键或值)。有任何想法吗?
采纳答案by Joseph jun. Melettukunnel
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/上的代码似乎不起作用。
回答by Malcolm
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:
如果我正确理解您的 XAML,字典中的每个对象都有一个名为“文本”的字段,您正试图绑定到该字段。如果是这样并且您进行了上述更改,则还需要更改您的 DataTemplate:
<TextBox Text="{Binding Text}" />
See this articlefor more info. HTH.
有关更多信息,请参阅这篇文章。哈。
回答by Subrai
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}"/>