2
votes

I have a button in a Listview column. When I press the button, the row does not select. I found one answer to the problem by using:

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

This works to select the row, but when the row loses focus it doesn't stay selected, and I need to be able to select multiple rows.

I also tried this solution:

 <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
        </Style>
 </ListView.ItemContainerStyle>

And in code behind:

private void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
    {
        ListViewItem item = (ListViewItem) sender;
        item.IsSelected = true;
    }

This is closer to what I want, but now this affect selecting multiple items and now the user has to click twice on another item before it will select.

I also tried re-selecting the row in the click handler by using:

ListViewItem selectedRow = ((FrameworkElement)sender).DataContext as ListViewItem;

and

((sender as FrameworkElement).TemplatedParent as ListViewItem).IsSelected = true;

but these give me a null error. Any suggestions for what I'm doing wrong?

I have to use a Listview for other reasons, or I would just use a Datagrid, which works great.

1

1 Answers

0
votes

Try adding a handler on the button click that reselects the row.