Steven Deam
Steven Deam

Reputation: 577

Select the row in a listbox when button in it is clicked

I'm assuming this is a simple thing that I am missing.

I have a ListBox in a WPF app that I am writing. Each row has a button to perform a simple action based on the row that the button is on. If the user clicks on the button directly then the SelectedItem on the ListBox is null. If I click in the row first, then click the button the SelectedItem is the row, as expected.

I want to be able to have the row that the button is on selected when the button is clicked. Again, I'm assuming that I am missing something simple, but my searches are coming up empty so far.

Upvotes: 2

Views: 1710

Answers (1)

Rohit Vats
Rohit Vats

Reputation: 81253

In case you want to select ListBoxItem on button click of ListBoxItem you can do this by attaching click handler to your button.

Assuming you have this XAML for ListBox declaration:

<ListBox x:Name="listBox" ItemsSource="{Binding SourceCollection}">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <Button Content="{Binding PropertyName}" Click="Button_Click"/>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

you can select listBoxItem from handler:

private void Button_Click(object sender, RoutedEventArgs e)
{
    ListBoxItem selectedItem = (ListBoxItem)listBox.ItemContainerGenerator.
                               ContainerFromItem(((Button)sender).DataContext);
    selectedItem.IsSelected = true;
}

Access DataContext of button which will be same as that of ListBoxItem. Hence, with it you can get container element i.e. ListBoxItem from ItemContainerGenerator.

Set IsSelected to True on fetched listBoxItem.

Upvotes: 4

Related Questions