2017-01-21 73 views
0

我有一個類WPF綁定字典<串,列表<Person>>到列表視圖由

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

這被存儲在Dictionary<string, List<Person>> m_PersionDict;

我想顯示此詞典中由組列表視圖.. 。組名是字典的關鍵..

喜歡的東西:

enter image description here

這裏的男性和女性都在字典中的不同的鍵..

謝謝...

+0

你可能要一個TreeView – 0x4f3759df

+1

你寧願_「扁平化」 _你的數據結構,並繼續執行所示[這裏](http://www.wpf-tutorial.com/listview-control/listview -grouping /)。 – jsanalytics

+0

@jstreet這將是我的最後一個選擇..如果有一種方法來從列表中通過數據綁定填充列表視圖..我會採取... –

回答

2

有這樣的沒有簡單的方法,即直接綁定到Dictionary<string, List<Person>>並應用PropertyGroupDescriptonICollectionView ,但你可以很容易地轉換字典匿名對象的列表,然後按Key屬性和往常一樣:

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> 
+0

var selectedItem =(dynamic)lv.SelectedItems [0]; string name = selectedItem.Name;字符串時間= selectedItem.Age; –

相關問題