【问题标题】:Loop through dictionary key in XAML ? (WPF)遍历 XAML 中的字典键? (WPF)
【发布时间】:2017-12-13 09:01:33
【问题描述】:

我想用字典中的新数据网格 foreach 键动态创建视图。是否可以在 XAML 中执行此操作?

我的字典是:
字典> 关键是字典的标题,对象列表将显示在数据网格中。 我想在我的字典中生成一个数据网格 foreach 键。

例如,如果我的字典中有这些条目:

<"Toto", [{"prop1":"tata", "prop2":"titi"}, {"prop1":"tata2", "prop2":"titi2"}]>  
<"Tutu", [{"prop1":"tatax", "prop2":"titix"}]>  

我想在我的程序中显示这个:

    TOTO                          TUTU
-------------                --------------
Prop1 | Prop2                Prop1  | Prop2  
------|------                -------|------
tata  | titi                 tatax  | titix  
tata2 | titi2  

在 ASP.NET 中,您可以在视图中间使用 @foreach 来实现,但如何在 XAML / WPF 中生成它?

【问题讨论】:

  • 使用 ItemsControl 与适当的 ItemsPanel 和 ItemTemplate 并将 ItemsSource 绑定到字典
  • 你有例子吗?我知道如何在我的对象列表上直接绑定数据网格,但我不知道如何处理我的字典(而且我没有找到任何示例)...
  • 字典实现了 KeyValuePair 的 IEnumerable。 ItemsControl 的一般方法在这里适用。 ItemsControl 有很多例子
  • 这里有一个例子:stackoverflow.com/a/47461158/5605739
  • 谢谢,它运行良好,正是我需要的。 @CelsoLívero 你的例子对我帮助很大。如果其他人有同样的问题,我只会用生成的代码来问我的问题。

标签: c# wpf xaml dictionary


【解决方案1】:

这是我在@ASh 和@CelsoLívero 的帮助下完成的代码工作代码,我只是发布它以帮助其他人,如果他们有同样的问题。

我的字典中有一个List&lt;Tag&gt;,这就是为什么我需要输入OneWay(因为它是一个只读数据网格,它可以满足我的需要)但是如果有人想要一个TwoWaybinding ,您将需要创建一个ObservableCollection 而不仅仅是一个List

<ItemsControl x:Name="itemControlTags" 
        ItemsSource="{Binding CurrentModuleItem.DicoTags}"  
        ScrollViewer.CanContentScroll="True"
        ScrollViewer.VerticalScrollBarVisibility="Auto"
        ScrollViewer.HorizontalScrollBarVisibility="Auto"
        >
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal"  
                Background="White"
                Width="{Binding ActualWidth, ElementName=itemControlTags}" 
                Height="{Binding ActualHeight, ElementName=itemControlTags}"  />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock Text="{Binding Key}"></TextBlock>
                <DataGrid AutoGenerateColumns="True" 
                  CanUserAddRows="False" 
                  IsReadOnly="True" 
                  CanUserDeleteRows="False" 
                  Name="TagsDatagrid"
                  ItemsSource="{Binding Path=Value, Mode=OneWay}">
                </DataGrid>
            </StackPanel>

        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

【讨论】:

  • 好的,现在将答案标记为正确,恭喜
  • 我会,但它说“你可以在 2 天内接受你自己的答案”所以,我会再等两天
猜你喜欢
  • 2014-05-15
  • 1970-01-01
  • 2021-11-23
  • 2022-01-14
  • 1970-01-01
  • 2015-04-16
  • 1970-01-01
  • 1970-01-01
  • 2013-05-18
相关资源
最近更新 更多