Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expander as ListBoxItem doesn't trigger Selection

Tags:

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 <code>ListBoxItem</code> resulting a <code>SelectedItem</code>

Clicking on Expander resulting in no SelectedItem update (click was on Expander 1 as evident by dashed outline):

Clicking on Expander resulting no <code>SelectedItem</code> update

like image 539
Maverik Avatar asked Jan 25 '13 12:01

Maverik


1 Answers

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>
like image 125
LPL Avatar answered Oct 23 '22 01:10

LPL