【问题标题】:WPF bind dictionary<string, List<Person>> to listview by groupWPF 按组将字典<string, List<Person>> 绑定到列表视图
【发布时间】:2017-01-21 21:47:16
【问题描述】:

我有课

class Person
{
  public string Name..get...
  public string Age...get... 
}

这存储在Dictionary&lt;string, List&lt;Person&gt;&gt; m_PersionDict;

我想按组在列表视图中显示这个字典...组名是字典的键..

类似:

这里的男性和女性是字典中的不同键..

谢谢...

【问题讨论】:

  • 你可能想要一个 TreeView
  • 您更愿意“扁平化”您的数据结构并按照HERE 所示继续操作。
  • @jstreet 这将是我的最后一个选择。如果有一种方法可以通过数据绑定从字典中填充列表视图。我会接受...
  • @Patrick 如何将列标题添加到树视图?特别是通过 xaml...
  • @HariPanicker :另外,通过 "hardcoding" 在您的Dictionary 中进行分组本身违背了让CollectionViewSource 为您做这件事的全部目的。如果以后您想更改分组,则不能:它是 "baked-in" 在您的数据结构中。

标签: c# wpf listview dictionary


【解决方案1】:

没有简单的方法可以做到这一点,即直接绑定到Dictionary&lt;string, List&lt;Person&gt;&gt; 并将PropertyGroupDescripton 应用于ICollectionView,但是您可以轻松地将字典转换为匿名对象列表,然后按像往常一样的关键属性:

public MainWindow()
{
    InitializeComponent();

    //the dictionary
    Dictionary<string, List<Person>> m_PersionDict = new Dictionary<string, List<Person>>();
    m_PersionDict.Add("Male", new List<Person>()
            {
                new Person() { Name = "John Doe", Age = 42 },
                new Person() { Name = "Sammy Doe", Age = 13 }
            });
    m_PersionDict.Add("Female", new List<Person>()
            {
                new Person() { Name = "Jane Doe", Age = 39 }
            });

    var flattened = m_PersionDict.SelectMany(x => x.Value.Select(y => new { Key = x.Key, Name = y.Name, Age = y.Age })).ToList();
    lv.ItemsSource = flattened;

    CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(lv.ItemsSource);
    PropertyGroupDescription groupDescription = new PropertyGroupDescription("Key");
    view.GroupDescriptions.Add(groupDescription);
}

这不应该有任何实际后果,而且是一个很小的代价。

<ListView Name="lv">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
        </GridView>
    </ListView.View>
    <ListView.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <TextBlock FontWeight="Bold" FontSize="14" Text="{Binding Name}"/>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
        </GroupStyle>
    </ListView.GroupStyle>
</ListView>

【讨论】:

  • var selectedItem = (动态)lv.SelectedItems[0];字符串名称= selectedItem.Name; string age= selectedItem.Age;
猜你喜欢
  • 2018-12-27
  • 2014-01-31
  • 1970-01-01
  • 2011-02-21
  • 1970-01-01
  • 2023-04-08
  • 2017-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多