Tobias Moe Thorstensen
Tobias Moe Thorstensen

Reputation: 8981

Listbox.ItemContainerStyle selected item

I have a list box with an ItemContainerStyle which describes the style of each element in the listbox. Like looks something like this:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem" BasedOn="{StaticResource MyStyle}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Border BorderThickness="0,0,0,1" BorderBrush="#1f000000"  Padding="16 8">
                        <Button Command={Binding MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=lists:MyControl}}}" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

The thing is that, when I click this button I want to know the SelectedItem in the listbox, which is bound in my ViewModel. This selection doesnt trigger unless I select the item first.

Any Ideas?

Upvotes: 1

Views: 2348

Answers (1)

Rom
Rom

Reputation: 1193

You need to force the IsSelected with a trigger:

 <Style.Triggers>
       <Trigger Property="IsKeyboardFocusWithin" Value="True">
                 <Setter Property="IsSelected" Value="True"/>
       </Trigger>
 </Style.Triggers>

Here is a full working example:

 <ListBox x:Name="ListBox" ItemsSource="{Binding SomeList}" SelectedItem="{Binding SelectedListElement, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True" >
    <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem" >
                <Style.Triggers>
                    <Trigger Property="IsKeyboardFocusWithin" Value="True">
                        <Setter Property="IsSelected" Value="True"/>
                    </Trigger>
                </Style.Triggers>
                <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Border BorderThickness="0,0,0,1" BorderBrush="#1f000000"  Padding="16 8">
                                <Button Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}},
                                Path=DataContext.Run}" CommandParameter="{Binding}"  Height="30" Width="100"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
 </ListBox>

Upvotes: 4

Related Questions