2014-02-17 101 views
9

我想組我收集這是基於我的以下模型:列表框分組問題

public class Person 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public Role PersonRole { get; set; } 
} 

public class Role 
{ 
    public int Id { get; set; } 
    public string RoleName { get; set; } 
} 

我PersonCollection,

public ObservableCollection<Person> PersonList; 

收集填充有三個Person對象,兩次與相同角色。

我想根據他們的RoleName將所有人分組。我有以下XAML:

​​

但是,呈現的UI沒有在列表框中顯示分組的RoleName。此外,我想水平地顯示分組,這些分組的項目是水平顯示的,而分組的項目是垂直顯示的。提前感謝任何幫助。

下面是我看到的輸出: enter image description here

+0

你想要很多...;)發佈我們的例子,所以我們可以工作。 –

+0

那麼,其實我只是想弄清楚爲什麼沒有顯示RoleName。橫向分組雖然是次要問題。 – Lucifer

+0

只需發佈代碼。我不想通過所有模板和測試數據工作。你已經擁有了它們。 –

回答

19

既然你已經在你的CollectionViewSource已經提供GroupDescriptons,groupStyle會選擇屬性名稱從那裏而已。

所有你需要的是綁定CollectionViewGroupName屬性來訪問其上應用分組屬性的值。在組風格中,綁定是針對CollectionViewGroup類的,而不是針對您的Model類的。

所以,這是你會怎麼做:

<TextBlock Text="{Binding Name}" FontWeight="Bold" 
      Background="ForestGreen" Margin="0,5,0,0"/> 

和關於水平對齊組,你可以設置集團ItemsPanelTemplateVirtualizingStackPanelOrientation設置爲Horizontal使您的組是水平排列。

<ListBox.GroupStyle> 
    <GroupStyle> 
     <GroupStyle.Panel> 
     <ItemsPanelTemplate> 
      <VirtualizingStackPanel Orientation="Horizontal"/> 
     </ItemsPanelTemplate> 
     </GroupStyle.Panel> 
     <GroupStyle.HeaderTemplate> 
     <DataTemplate> 
      <TextBlock Text="{Binding Name}" FontWeight="Bold" 
         Background="ForestGreen" Margin="0,5,0,0"/> 
     </DataTemplate> 
     </GroupStyle.HeaderTemplate> 
    </GroupStyle> 
</ListBox.GroupStyle> 
+3

謝謝,Rohit。你的解釋讓我很容易理解。 – Lucifer

+0

不客氣Lucifer。樂意效勞..!! :) –

+1

這節省了我的一天,非常感謝! –