获取WPF数据网格上下文菜单单击行

编程入门 行业动态 更新时间:2024-10-27 16:33:53
本文介绍了获取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数据网格上下文菜单单击行

本文发布于:2023-11-23 02:22:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1619735.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上下文   网格   单击   菜单   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!