how to right click on item from Listbox and open menu on WPF

前端 未结 2 2011
清歌不尽
清歌不尽 2021-02-07 17:37

i have Listbox with files in, i want to able to right click and open a menu like Delete in order to remove files from the Listbox.

currently i have this function after r

2条回答
  •  清歌不尽
    2021-02-07 18:01

    You already have a context menu with your markup.

    If you want to perform some operation, one of the ways is to check which item was clicked in the menu's Click function. For example, you have the next listbox:

    
        
             
                 
             
        
    
        ...
        ...
        ...
    
    
    

    And function may be next:

    private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
    {
        if (someListBox.SelectedIndex == -1) return;
    
        // Hypothetical function GetElement retrieves some element
        var element = GetElement(someListBox.SelectedIndex);
    
        // Hypothetical function DeleteElement
        DeleteElement(element);
    }
    

    Updated 5 March 2012:

    Here is another variant of your listbox. You can add a context menu not to listbox but to the listbox items. For example:

    
        
    
            
            
                
            
    
            
            
    
        
        ...
        ...
        ...
    
    

    1) This function will unsellect all items when you clicked on the empty space in the listbox:

    private void someListBox_MouseDown(object sender, MouseButtonEventArgs e)
    {
        someListBox.UnselectAll();
    }
    

    2) When you click the lisboxt item, it is blue. When you right click the listbox item, it is still blue, but if a context menu appears, the listbox item becomes gray, maybe it is so because this item loses a focus.

    3) Delete function works fine:

    private void MenuItemDelete_Click(object sender, RoutedEventArgs e)
    {
        if (someListBox.SelectedIndex == -1)
        {
            return;
        }
    
        someListBox.Items.RemoveAt(someListBox.SelectedIndex);
    }
    

提交回复
热议问题