views:

421

answers:

1

I have a ListBox with databinding. I need to fire an event when a user clicks on one of the ListBoxItems, but I can't quite work out how to do that. I tried putting a Grid on the ListBox.ItemTemplate and putting the MouseDown event on that:

<ListBox
    Name="popupListBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid MouseDown="Grid_MouseDown" Background="Aquamarine">
                <TextBlock Text="{Binding Path=TagText}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

However the grid is usually smaller than the actual ListBoxItem. I can't work out how to get it to fire when any part of it is clicked.

I've tried looking at the SelectionChanged event on the ListBox, but that doesn't fire when you click on the currently selected item.

I've also tried editing the style for the ListBoxItem, but I can't figure out how to correctly apply a MouseDown event to it; I always get syntax errors.

A: 

You could add an ItemContainerStyle to stretch the DataTemplate to fill the available horizontal space. The mouse down events would now fire anywhere you click on the item.

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

    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid MouseDown="Grid_MouseDown" Background="Aquamarine">
                <TextBlock Text="{Binding Path=tagText}" />
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Oren Trutner
That's close, but there's a few pixels on the left that aren't covered by the content. I was hoping that there would be a cleaner solution.
RandomEngy
Alright if I add <Setter Property="Padding" Value="0" /> to the ItemContainerStyle and re-add the padding on the TextBlock, it seems to work. Thanks for the tip.
RandomEngy