Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouped WPF ListView Styling issue with margin

Tags:

.net

listview

wpf

There is a tiny margin on the left side in the style when using the grouping functionality of the ListView in WPF.

Sample of ListView with grouping problem (margin):

ListView, group by name

Sample of ListView without grouping (want same style of item in grouped list):

ListView, without grouping

Question:

How to remove the margin/padding? The (selected) item in the grouped list should fill the same space as in the ungrouped list.

Update:

            <ListView Margin="20,0,0,0" ItemsSource="{Binding ItemsView}" SelectedItem="{Binding SelectedItem}" IsSynchronizedWithCurrentItem="True"  SelectionMode="Single" BorderThickness="0" Background="Transparent">
                <ListView.GroupStyle>
                    <GroupStyle>
                        <GroupStyle.HeaderTemplate>
                            <DataTemplate DataType="data:Item">
                                <DockPanel HorizontalAlignment="Stretch">
                                    <TextBlock Text="{Binding Name}" FontWeight="Bold" Margin="0,5,5,5" />
                                    <Separator  />
                                </DockPanel>
                            </DataTemplate>
                        </GroupStyle.HeaderTemplate>
                    </GroupStyle>
                </ListView.GroupStyle>
                <ListView.ItemTemplate>
                    <DataTemplate DataType="data:Item">
                        <TextBlock Margin="10,10,10,10" Text="{Binding Name}" />
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
like image 433
Beachwalker Avatar asked Aug 11 '14 09:08

Beachwalker


1 Answers

When grouping is used in a CollectionViewSource (I'm assuming you are using one), the, Groups will be visualized by a GroupItem. The default style of a GroupItem looks like this (obtained with StyleSnooper):

<Style TargetType="{x:Type GroupItem}" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type GroupItem}">
                <StackPanel>
                    <ContentPresenter Content="{TemplateBinding ContentControl.Content}" ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}" ContentStringFormat="{TemplateBinding ContentControl.ContentStringFormat}" />
                    <ItemsPresenter Margin="5,0,0,0" />
                </StackPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

As you can see, there is a Margin on the ItemsPresenter. A solution is to create your own style for the GroupItem, and remove the Margin on the ItemsPresenter, and set the GroupStyle.ContainerStyle to use this style.

like image 121
Roel van Westerop Avatar answered Nov 11 '22 17:11

Roel van Westerop