0

I have a grid, and I want to add onclick event.

<ListView 
    HorizontalAlignment="Stretch"
    Margin="10"
    x:Name="BooksListView"
    GridViewColumnHeader.Click="SortBooks"
    >
    <ListView.View>
        <GridView></GridView>
    </ListView.View>
</ListView>

I've tried the accepted answer from this SO question, but item.IsSelected is always false.

<ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDown" />
        </Style>
    </ListView.ItemContainerStyle>

C# code:

private void ListViewItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var item = sender as ListViewItem;
    if (item != null && item.IsSelected) // IsSelected is always false
    ...
}

Should I just remove this check, or there is a better way to do it?

Community
  • 1
  • 1
Matt
  • 67
  • 7
  • You can remove this check if it's not critical for your business logic. – Alexander Bell Mar 26 '16 at 03:57
  • You can set the item.IsSelected to true if you need to but I suspect that the property will get set just after the event handler method finishes. I would definitely recommend you use the MouseLeftButtonDown, MouseDown, or MouseLeftButtonUp event and not the preview event. Selecting the item is what raises the event and executes the handler so you can be assured that IsSelected will be true. Just get rid of that check or use non preview event. I tend to use MouseUp event so can drag mouse off item and let go if accidentally selected and item. – SimperT Mar 26 '16 at 04:12
  • @Matt Did the answer work for you? – Paul MacGuiheen Mar 26 '16 at 20:14

1 Answers1

0

It's a preview event so it's not yet reached the item to make it selected. That is why item.IsSelected always returns false for you.

More info is available here What are WPF Preview Events?

Basically preview events are handled if say you want to cancel an event before it reaches it's target. It is more common to handle the 'bubbling' type of events. Maybe you should try MouseLeftButtonDown. There's a little more comparison here Difference between PreviewMouseLeftButtonDown and MouseLeftButtonDown WPF

Community
  • 1
  • 1
Paul MacGuiheen
  • 628
  • 5
  • 17