如何在代码后面创建动态GroupStyle?

时间:2016-05-01 18:57:29

标签: c# wpf

我发现可以解决多个标头问题的ListView.GroupStyle。假设我在XAML中列出了这个列表:

<ListView x:Name="Match">
     <ListView.View>
            <GridView>
                   <GridViewColumn Header="Time" Width="50" DisplayMemberBinding="{Binding Time}" />
                   <GridViewColumn Header="Minute" Width="70" DisplayMemberBinding="{Binding Minute}"/>
                   <GridViewColumn Header="Home" Width="Auto" DisplayMemberBinding="{Binding Home}"/>
                   <GridViewColumn Header="Away" Width="Auto" DisplayMemberBinding="{Binding Away}"/>
                   <GridViewColumn Header="1 Time" Width="80" DisplayMemberBinding="{Binding Result}"/>
                   <GridViewColumn Header="2 Time" Width="80" DisplayMemberBinding="{Binding MatchSecondTime}"/>
            </GridView>
      </ListView.View>

现在假设我想在this example中添加多个GroupStyle。 如何在代码后面创建GroupStyle?

我实际上尝试过:

Style myStyle = new Style(typeof(GroupItem));
Setter setter = new Setter();
setter.Property = MarginProperty;
setter.Value = new Thickness(0, 0, 0, 0);
myStyle.Setters.Add(setter);

Setter setterTemplate = new Setter();
setter.Property = TemplateProperty;
setter.Value = Template;

GroupStyle gs = new GroupStyle();
gs.ContainerStyle = myStyle;
Match.GroupStyle.Add(gs);

但我无法像示例中那样设置标题名称:

enter image description here

我的目标是创建示例GroupStyle中显示的Male, Female标头。有人可以告诉我怎么样?

1 个答案:

答案 0 :(得分:1)

我从你的other question here看到,你想要按国家分组,非常好。

我建议如下:

public class MatchResults{
   public DateTime Time {get;set;}
   public int Minute {get;set;}
   public string Home {get;set;}
   public string Away {get;set;}
   public string 1-Time {get;set;}
   public string 2-Time {get;set;}
   public CountryType Country {get;set}
} 

然后按照枚举

进行分组
enum CountryType{
  Austria,
  Azerbaijan,
  Belgium,...
}

然后在您的窗口构造函数中,在InitializeComponent()之后,您将初始化数据项并将它们添加到列表中,并将它们作为XAML中ListView的数据源(从the link复制大部分代码) )。 然后是构造函数的最后3行,你用Country参数替换Sex参数:

CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(lvUsers.ItemsSource);
PropertyGroupDescription groupDescription = new PropertyGroupDescription("Country");
view.GroupDescriptions.Add(groupDescription);