I've got a ListBox
with ListBoxItem
using a DataTemplate
that uses Expander
as its container. The problem is that Expander
appears to be eating up Click
event (HeaderSite
part of Expander
to be exact) and I never get the SelectedItem
if I click on Expander
(but it works if you click on ListBoxItem
itself).
Any idea on how to get Expander
to play nicely with ListBox
?
Here's a simplified Xaml that will reproduce the problem (no code behind needed):
Edit Code updated to bring closer to my actual template but screenshots are still from previous revision (the problem is same - this is just to clarify problem with first answer)
<Window x:Class="ListBoxSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBlock>
<Run Text="Selected Item" />
<Run Text="{Binding ElementName=ListBox, Path=SelectedItem}" />
</TextBlock>
<ListBox x:Name="ListBox">
<ListBoxItem>
<Expander Header="Expandable Stuff 1">
<ListBox>
<ListBoxItem>1.1</ListBoxItem>
<ListBoxItem>1.2</ListBoxItem>
</ListBox>
</Expander>
</ListBoxItem>
<ListBoxItem>
<Expander Header="Expandable Stuff 2">
<ListBox>
<ListBoxItem>2.1</ListBoxItem>
<ListBoxItem>2.2</ListBoxItem>
</ListBox>
</Expander>
</ListBoxItem>
</ListBox>
</StackPanel>
</Window>
Screenshots are pre-edit
Clicking on ListBoxItem
resulting a SelectedItem
:
Clicking on Expander resulting in no SelectedItem
update (click was on Expander 1 as evident by dashed outline):
Without code behind you could do this
<ListBox.ItemContainerStyle>
<Style>
<Style.Triggers>
<EventTrigger RoutedEvent="Control.PreviewMouseLeftButtonDown">
<BeginStoryboard>
<Storyboard Storyboard.TargetProperty="(Selector.IsSelected)">
<BooleanAnimationUsingKeyFrames Duration="0:0:0">
<DiscreteBooleanKeyFrame Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With