views:

37

answers:

2

I have a listbox with a datatemplate for the items. The problem is that selecting an item doesn't work by just clicking anywhere on the item; I have to click on a specific sub-element for it to actually work.

My item has an image and a textblock. If I hover the mouse over the image or text-block, I actually see the hover-effect. If I hover the mouse over any of the 'empty' space of the item, no hover effect (and no selection when I click there).

Example image : http://i33.tinypic.com/wvtleg.png

If I click on (or hover over) the actual text or the image it works fine, but if i hover my mouse in the empty areas (I've drawn a red line around it :)) the listbox doesn't respond.

How do I get the listbox hovering / clicking to respond to clicking anywhere in the item's space ?

For completeness here is my Listbox + template:

<ListBox Grid.Row="1"
  ItemsSource="{Binding Path=CreatableOutputWindows, Mode=OneWay}" Height="Auto"
  HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
  Margin="8,8,8,8"
  Name="listBox1" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="84"/>
          <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Border Margin="5" BorderBrush="Black" BorderThickness="2">
          <Image Source="{Binding Path=Image}" Stretch="Fill" Width="80" Height="50" />
        </Border>
        <StackPanel Grid.Column="1" Margin="5">
          <StackPanel Orientation="Horizontal" TextBlock.FontWeight="Bold">
            <TextBlock Text="{Binding Path=Name}" />
          </StackPanel>
        </StackPanel>
      </Grid>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
A: 

It sounds like your ListBoxItem is not responding to hit testing. Try setting the Background of the Grid to Transparent:

<Grid Background="Transparent">

The default value is null, which will make the element invisible to hit testing. Setting the background to transparent will not affect the display but will allow the element to be hit. The default style for ListBoxItem will have a Transparent background, but you may have restyled it.

Quartermeister
+1  A: 

As Quartermeister pointed out - you need to set the Background of the Grid - but you also need to set the following style in your resources as ListBoxItems' HorizontalContentAlignment is set to Left by default. (It isn't enough to set it on the ListBox)

<ListBox.Resources>
    <Style TargetType="{x:Type ListBoxItem}">
        <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
    </Style>
</ListBox.Resources>
Goblin
Thanks, this worked.
IUsedToBeAPygmy