WPF ListView - detect when selected item is clicked

前端 未结 7 952
刺人心
刺人心 2020-11-29 02:10

I\'m using a WPF ListView control which displays a list of databound items.


    
                 


        
7条回答
  •  心在旅途
    2020-11-29 02:36

    I couldn't get the accepted answer to work the way I wanted it to (see Farrukh's comment).

    I came up with a slightly different solution which also feels more native because it selects the item on mouse button down and then you're able to react to it when the mouse button gets released:

    XAML:

    
    
        
    
    

    Code behind:

    private void ListViewItem_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        MyListView.SelectedItems.Clear();
    
        ListViewItem item = sender as ListViewItem;
        if (item != null)
        {
            item.IsSelected = true;
            MyListView.SelectedItem = item;
        }
    }
    
    private void ListViewItem_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        ListViewItem item = sender as ListViewItem;
        if (item != null && item.IsSelected)
        {
            // do stuff
        }
    }
    

提交回复
热议问题