获取WPF数据网格上下文菜单单击行 [英] Getting WPF Data Grid Context Menu Click Row

查看:76
本文介绍了获取WPF数据网格上下文菜单单击行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个WPF DataGrid

I have a WPF DataGrid

<DataGrid AutoGenerateColumns="False"  Name="dataGrid1"  IsReadOnly="True" >
<DataGrid.Columns>
    <DataGridTextColumn Header="Site" Binding="{Binding Site}" Width="150" />
    <DataGridTextColumn Header="Subject" Binding="{Binding Subject}" Width="310" />
</DataGrid.Columns>
<DataGrid.ContextMenu>
    <ContextMenu>
        <MenuItem Header="Delete" Click="Context_Delete">
            <MenuItem.Icon>
                <Image Width="12" Height="12" Source="Images/Delete.png" />
            </MenuItem.Icon>
        </MenuItem>
    </ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>

我的点击事件处理程序为:

I have the click event handler as:

private void Context_Delete(object sender, System.EventArgs e)  { }

如何获得单击之前上下文菜单所在的行? 发件人对象是 System.Windows.Controls.MenuItem ,而不是 DataGridRow 。如何获得单击上下文菜单的 DataGridRow (我在文件后面的代码中设置了 DataGrid.ItemSource 。)

How do I get the row on which the Context Menu was before the click? The sender object is System.Windows.Controls.MenuItem, not the DataGridRow. How do I get the DataGridRow where the Context Menu was clicked. (I set the DataGrid.ItemSource in the code behind file.)

推荐答案

因此,根据您的示例代码,我假定您将DataGrid绑定到对象的ObservableCollection,并将对象的属性绑定到Site和Subject到DataGridColumns。

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.

本质上,您要做的就是找出与单击的DataGridRow绑定的项目是什么,然后从ObservableCollection中删除该项目。下面是一些示例代码,可以帮助您入门:

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);
}

这篇关于获取WPF数据网格上下文菜单单击行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆