如何在GroupItem中显示自定义文本?

epa*_*alm 2 c# wpf xaml grouping

带Expander的典型ListView GroupStyle看起来大致如下:

<ListView.GroupStyle>
    <GroupStyle>
        <GroupStyle.ContainerStyle>
            <Style TargetType="{x:Type GroupItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type GroupItem}">
                            <Expander>
                                <Expander.Header>
                                    <TextBlock Text="{Binding Path=Name}" />
                                </Expander.Header>
                                <Expander.Content>
                                    <ItemsPresenter />
                                </Expander.Content>
                            </Expander>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </GroupStyle.ContainerStyle>
    </GroupStyle>
</ListView.GroupStyle>
Run Code Online (Sandbox Code Playgroud)

TextBlock绑定到Name,它似乎生成GroupItem对象的值,该对象的propertyName被传递到PropertyGroupDescription,后者被添加到ListCollectionView的GroupDescriptions集合(whew):

class MyClass
{
    public int Id { get; set; }
    public int FullName { get; set; }
    public string GroupName { get; set; } // used to group MyClass objects
}

MyView.GroupDescriptions.Add(new PropertyGroupDescription("GroupName"));
Run Code Online (Sandbox Code Playgroud)

如何让ListView的组标题显示GroupName以外的属性?我要说的是GroupName对于将我的对象拆分成组是有用的,但不一定是我希望用于所述组的标题的名称.

LPL*_*LPL 7

CollectionViewGroup.Name属性的类型为object.这意味着您的GroupName属性不能是字符串.尝试这样的事情

class MyClass
{
    ...
    public MyGroup GroupName { get; set; } // used to group MyClass objects
}

class MyGroup
{
    public string HeaderText { get; set; }
    // maybe you will need an additional property to make this object
    // unique for grouping (e.g. for different groups with same HeaderText)
}
Run Code Online (Sandbox Code Playgroud)

.

<Expander.Header>
    <TextBlock Text="{Binding Path=Name.HeaderText}" />
</Expander.Header>
Run Code Online (Sandbox Code Playgroud)

  • 另外:用作组属性的类必须覆盖 bool Equals(object obj)。 (2认同)