Fisheer
Fisheer

Reputation: 77

Clicking on the white space won't trigger the event in ListBox

I created a ListBox with TextBlocks in it that each have a MouseLeftButtonUp event. The size of the ListBox is wider than the text and when I click on the white space next to the text in the ListBox the event won't trigger. It still selects the item, covering it in blue, but the event won't trigger until I click on the text.

<ListBox Name="myListBox" Grid.Row="1" Margin="10, 0, 10, 10">
    <TextBlock Name="X2" Text="X2, Power Head" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_X2" />
    <TextBlock Name="UB2X" Text="UB2X, Cab Car" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_UB2X" />
    <TextBlock Name="UA2" Text="UA2, 1st Class" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_UA2" />
    <TextBlock Name="UB2" Text="UB2, 2nd Class" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_UB2" />
    <TextBlock Name="URB2" Text="URB2, Bistro" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_URB2" />
    <TextBlock Name="URB2A" Text="URB2A, Bistro A" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_URB2A" />
</ListBox>

Upvotes: 0

Views: 39

Answers (1)

thatguy
thatguy

Reputation: 22119

Set an ItemContainerStyle to stretch the ListBoxItem content (your TextBlocks) to the full width.

<ListBox Name="myListBox" Grid.Row="1" Margin="10, 0, 10, 10">
   <ListBox.ItemContainerStyle>
      <Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
         <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
      </Style>
   </ListBox.ItemContainerStyle>
   <TextBlock Name="X2" Text="X2, Power Head" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_X2" />
   <TextBlock Name="UB2X" Text="UB2X, Cab Car" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_UB2X" />
   <TextBlock Name="UA2" Text="UA2, 1st Class" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_UA2" />
   <TextBlock Name="UB2" Text="UB2, 2nd Class" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_UB2" />
   <TextBlock Name="URB2" Text="URB2, Bistro" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_URB2" />
   <TextBlock Name="URB2A" Text="URB2A, Bistro A" Margin="0, 3, 0, 0" MouseLeftButtonUp="Selected_URB2A" />
</ListBox>

Upvotes: 2

Related Questions