soaloa
soaloa

Reputation: 61

Listbox doesn't detect selected item

I have the following listbox:

<ListBox ItemsSource="{Binding AvailableTemplates}" Style="{DynamicResource SearchListBoxStyle}" SelectedItem="{Binding SelectedTemplate, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <RadioButton Content="{Binding}" GroupName="group" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

this doesn't detect as selected item changed if i select on the radiobutton. It only detects if i click under the radio button on the listbox row. Any ideeas how to amend to detect as selected item changed when clicking on the radio button?

Upvotes: 1

Views: 3653

Answers (3)

sdd
sdd

Reputation: 721

Try setting ListBoxItem.IsHitTestVisible to false (you may do this in xaml). It solved my selection problem elementary. My problem was that selection only worked when I clicked on white space in ListBox line but not a custom content.

Upvotes: 1

Rachel
Rachel

Reputation: 132558

If you only want to synchronize the RadioButton.IsChecked with ListBoxItem.IsSelected, you can use a binding

<RadioButton Content="{Binding}" GroupName="group"
             IsChecked="{Binding Path=IsSelected, RelativeSource={
                 RelativeSource AncestorType={x:Type ListBoxItem}},Mode=TwoWay}"/>

If you don't want your items synchronized, you can use a Trigger that sets IsSelected whenever the item gets keyboard focus, although this will only keep an item selected as long as it has keyboard focus

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

And if you want it selected regardless of if the element still has keyboard focus or not, you have to use a little code behind

<Style TargetType="{x:Type ListBoxItem}">
    <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>
protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
    ListBoxItem item = (ListBoxItem)sender;
    item.IsSelected = true;
}

Upvotes: 8

J. Lennon
J. Lennon

Reputation: 3361

You can not mistake: listBox.SelectedItem and radioButton.IsChecked

They are totally different things, SelectedItem is called the ListBoxItem, your radiobutton is within a listboxitem.

You must make a binding for property IsChecked (RadioButton).

Upvotes: 1

Related Questions