2011-04-15 90 views
1

我有一個DataGrid,看起來像這樣。如何在DataGrid分組中自定義組頁眉?

enter image description here

我按性別分組的數據。我GroupItem風格是

<Style TargetType="{x:Type GroupItem}"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="{x:Type GroupItem}"> 
        <Expander x:Name="exp" IsExpanded="True" 
         Background="White" 
         Foreground="Black"> 
         <Expander.Header> 
          <TextBlock Text="{Binding Name}"/> 
         </Expander.Header> 
         <ItemsPresenter /> 
        </Expander> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 

我希望我的組頭「男」和「女」,看起來像「性別:男」和「性別:女」,而不是簡單的純「男」和「女」。我如何修改我的GroupItem樣式來實現這個功能,以便每次我將數據分組到DataGrid中時,組頭可以顯示爲GroupHeaderTitle:GroupHeaderValue?或者是否需要更改GroupItem樣式以外的任何其他內容才能實現此目的?

回答

1

您可以添加屬性GroupTitle這在您的視圖模型表示所需的組標題,如果你正在使用MVVM或您的窗口代碼隱藏否則,再加入在這勢必給GroupTitle財產Expander.Header另一個TextBlock的,請參閱下面的代碼片段:

<Style TargetType="{x:Type GroupItem}"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type GroupItem}"> 
       <Expander x:Name="exp" IsExpanded="True" 
          Background="White" Foreground="Black"> 
        <Expander.Header> 
         <StackPanel Orientation="Horizontal"> 
          <TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, Path=DataContext.GroupTitle}"/> 
          <TextBlock Text="{Binding Name}"/> 
         </StackPanel> 
        </Expander.Header> 
        <ItemsPresenter /> 
       </Expander> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 
+0

這是一個硬編碼的解決方案。如果用戶按年齡分組怎麼辦? _「每次我在datagrid中對數據進行分組時,組頭可以顯示爲GroupHeaderTitle:GroupHeaderValue」_ – 2011-04-15 12:45:26

+0

@haris:是的,我更新了答案,現在檢查它。 – 2011-04-15 16:42:04

+1

我明白你的觀點,但我允許用戶做多個嵌套分組。基於財產的解決方案將再次成爲一種硬編碼解決方案。我想要一個可以適用於所有嵌套分組的通用解決方案。在我的場景中,完全取決於用戶是否希望按性別,年齡或任何其他列進行分組,並且類似地在任何分組內部,他可以通過任何其他列進行分組 – 2011-04-15 21:08:33

1

當您添加分組只是提供一個轉換器:

// Get the default view 
ICollectionView view = CollectionViewSource.GetDefaultView(...); 

// Do the grouping 
view.GroupDescriptions.Clear(); 
view.GroupDescriptions.Add(new PropertyGroupDescription("Gender", new GenderConverter())); 

// The converter 
public class GenderConverter : IValueConverter 
{ 
    public object Convert(object value, 
    Type targetType, object parameter, CultureInfo culture) 
    { 
     return string.Format("Gender: {0}", value); 
    } 

    public object ConvertBack(object value, 
    Type targetType, object parameter, CultureInfo culture) 
    { 
     return DependencyProperty.UnsetValue; 
    } 
}