【问题标题】:Bind Dictionary to ItemsControl in C#/WPF在 C#/WPF 中将字典绑定到 ItemsControl
【发布时间】:2010-11-09 00:43:07
【问题描述】:

我正在尝试将字典中的 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>

很遗憾没有任何文本框内容(可能是键或值)。 有什么想法吗?

【问题讨论】:

    标签: c# wpf dictionary itemscontrol


    【解决方案1】:

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

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

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

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

    <TextBlock Text="{Binding}"/>
    

    【讨论】:

      【解决方案2】:

      我用这条线解决了它:

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

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

      【讨论】:

        【解决方案3】:

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

        ItemsSource="{Binding Persons.Values}"
        

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

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

        请参阅this article 了解更多信息。 HTH。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-03-27
          • 1970-01-01
          • 2016-11-20
          • 2013-11-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多