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

时间:2013-01-21 20:24:39

标签: c# wpf xaml grouping

带扩展器的典型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>

TextBlock绑定到Name,它似乎生成GroupItem对象的值,该对象的propertyName被传递到PropertyGroupDescription,后者被添加到ListCollectionView的GroupDescriptions Collection(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"));

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

2 个答案:

答案 0 :(得分:7)

CollectionViewGroup.Name Property属于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)
}

<Expander.Header>
    <TextBlock Text="{Binding Path=Name.HeaderText}" />
</Expander.Header>

答案 1 :(得分:0)

简单如下:

<TextBlock Text="{Binding Path=Name, StringFormat='MyText: {0}'}" />