Remove Extra Space around Listbox

This is the default control template for ListBox:

    <ControlTemplate x:Key="ListBoxControlTemplate1" TargetType="{x:Type ListBox}">
        <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="1" SnapsToDevicePixels="True">
            <ScrollViewer Focusable="False" Padding="{TemplateBinding Padding}">
                <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
            </ScrollViewer>
        </Border>
        <ControlTemplate.Triggers>
            <Trigger Property="IsEnabled" Value="False">
                <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
            </Trigger>
            <Trigger Property="IsGrouping" Value="True">
                <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>

Notice the Padding="1" on Border named Bd. Since this is harcoded and not template bound, you can either retemplate the ListBox and set the padding to 0, or since Padding on the ScollViewer has a TemplateBinding to the Padding of the ListBox, you can set the Padding on your ListBox to -1 to offset the padding on the border.


The control template of a ListBox looks like this:

<ControlTemplate TargetType="{x:Type ListBox}">
    <Border Name="Bd"
            Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}"
            SnapsToDevicePixels="true"
            Padding="1"> <!-- This might be the problem -->
    <!-- ... -->

Tags:

Wpf

Xaml

Listbox