简体   繁体   中英

C# WPF Listbox Group Header Style

I'm using a Listbox to show multiple items. The items are grouped. Now I want to edit the header style but the only thing happens is that the text isn't shown anymore.

Thats my xaml:

<ListBox x:Name="lbTreatments" HorizontalAlignment="Left" Height="473" Margin="10,37,0,0" VerticalAlignment="Top" Width="309" FontSize="13">
    <ListBox.GroupStyle>
        <GroupStyle>
            <GroupStyle.HeaderTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding subcategoryName}" FontWeight="Bold"/>
                </DataTemplate>
            </GroupStyle.HeaderTemplate>
        </GroupStyle>
    </ListBox.GroupStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding name}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

And thats my code to group the items:

ICollectionView view = CollectionViewSource.GetDefaultView(treatmentsCategory);
view.GroupDescriptions.Add(new PropertyGroupDescription("subcategoryName"));
view.SortDescriptions.Add(new SortDescription("subcategoryName", ListSortDirection.Ascending));
lbTreatments.ItemsSource = view;

The items are grouped but the header text is missing. If I delete the Groupstyle from xaml the text will be shown. Can anybode help me please?

MSDN says:

Each group is of type CollectionViewGroup.

The actual data type is CollectionViewGroup which doesn't have a subcategoryName property so the binding will fail. Instead you have to use the Name property, which will already be set to the value from subcategoryName .

As such, use this...

<TextBlock Text="{Binding Name}"/>

...in your header template to get the group name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM