Search code examples
c#wpfxamlmvvmwpf-controls

WPF Click on control inside ListBoxItem does not select ListBoxItem


Hi I could not find any similar problem so I posted new question. In code below I create ListBox control with ListBoxItems that each contains radio button inside. When I click on the radio button it gets selects but parent ListBoxItem does not (ListBoxItem is not highlighted). How can I solve this issue?

<ListBox Margin="0, 5, 0, 0" ItemsSource="{Binding mySource, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!-- Rabio template -->
            <RadioButton GroupName="radiosGroup"
                     Margin="10, 2, 5, 2"
                     Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.SelectedSetting}"
                     CommandParameter="{Binding SomeId, Mode=OneWay}"
                     Content="{Binding FileNameWithoutExtensions, Mode=OneWay}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Solution

  • You can achieve this by applying the following ItemContainerStyle to your ListBox which uses Trigger on property IsKeyboardFocusWithin to select it.

    <ListBox>
        <ListBox.ItemContainerStyle>
          <Style TargetType="ListBoxItem">
             <Style.Triggers> 
               <Trigger Property="IsKeyboardFocusWithin" Value="True"> 
                  <Setter Property="IsSelected" Value="True"/> 
               </Trigger> 
             </Style.Triggers>
           </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>