Getting WPF Data Grid Context Menu Click Row

后端 未结 6 553
无人共我
无人共我 2021-01-31 10:30

I have a WPF DataGrid



    

        
6条回答
  •  粉色の甜心
    2021-01-31 10:41

    So based on your example code, I presume you bind your DataGrid to an ObservableCollection of objects of which you bind the properties Site and Subject to the DataGridColumns.

    Essentially, all you need to do is figure out what the item bound to the clicked DataGridRow is and remove that from your ObservableCollection. Here is some example code to get you started:

    private void Context_Delete(object sender, RoutedEventArgs e)
    {
        //Get the clicked MenuItem
        var menuItem = (MenuItem)sender;
    
        //Get the ContextMenu to which the menuItem belongs
        var contextMenu = (ContextMenu)menuItem.Parent;
    
        //Find the placementTarget
        var item = (DataGrid)contextMenu.PlacementTarget;
    
        //Get the underlying item, that you cast to your object that is bound
        //to the DataGrid (and has subject and state as property)
        var toDeleteFromBindedList = (YourObject)item.SelectedCells[0].Item;
    
        //Remove the toDeleteFromBindedList object from your ObservableCollection
        yourObservableCollection.Remove(toDeleteFromBindedList);
    }
    

提交回复
热议问题