How to capture a mouse click on an Item in a ListBox in WPF?

前端 未结 6 1364
长情又很酷
长情又很酷 2020-12-02 11:30

I want to get notified when an item in a ListBox gets clicked by the mouse, whether it is already selected or not.

I searched and found this: (http://kevin-berridge.

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 12:04

    There is also another way - to handle PreviewMouseDown event and check if it was triggered by the list item:

    In XAML:

     
    

    In codebehind:

    private void PlaceholdersListBox_OnPreviewMouseDown(object sender, MouseButtonEventArgs e)
    {
        var item = ItemsControl.ContainerFromElement(sender as ListBox, e.OriginalSource as DependencyObject) as ListBoxItem;
        if (item != null)
        {
            // ListBox item clicked - do some cool things here
        }
    }
    

    Was inspired by this answer, but it uses listbox by name, I propose to use sender argument to avoid unnecessary dependencies.

提交回复
热议问题