Stretch ListBox Items hit area to full width of the ListBox? ListBox style is set implicity through a theme

Nicholas picture Nicholas · Jan 8, 2011 · Viewed 9.2k times · Source

I've looked around for an answer on this, but the potential duplicates are more concerned with presentation than interaction.

I have a basic list box, and each item's content is a simple string.

The ListBox itself is stretched to fill it's grid container, but each ListBoxItem's hitarea does not mirror the ListBox width. It looks as if the hitarea (pointer contact area) for each item is only the width of the text content. How do I make this stretch all the way across, regardless of the text size.

I've set HorizontalContentAlignment to Stretch, but this doesn't solve my problem. My only other guess is that the content is actually stretching, but the background is invisible and so not capturing the mouse pointer.

<ListBox 
    Grid.Row="1"
    x:Name="ProjectsListBox" 
    DisplayMemberPath="Name"
    ItemsSource="{Binding Path=Projects}" 
    SelectedItem="{Binding Path=SelectedProject}"
    HorizontalContentAlignment="Stretch"/>

The XAML is pretty straight forward on this. If I mouse over the text in one of the items, then the entire width of the item becomes active. I guess I just need to know how to create an interactive background that is invisible.

Answer

Fredrik Hedblad picture Fredrik Hedblad · Jan 8, 2011

HorizontalContentAlignment="Stretch" should be set in ItemContainerStyle for this to work.

Xaml Example

<ListBox xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <ListBox.ItemsSource>
        <x:Array Type="{x:Type sys:String}">
            <sys:String>String 1</sys:String>
            <sys:String>String 2</sys:String>
            <sys:String>String 3</sys:String>
            <sys:String>String 4</sys:String>
        </x:Array>
    </ListBox.ItemsSource>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding}" Background="Green"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Update
Try this

<ListBox ...>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem" BasedOn="{StaticResource {x:Type ListBoxItem}}">
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListBox.ItemContainerStyle>