首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >获取WPF数据网格快捷菜单单击行

获取WPF数据网格快捷菜单单击行
EN

Stack Overflow用户
提问于 2013-05-30 04:10:57
回答 6查看 40.1K关注 0票数 24

我有一个WPF DataGrid

代码语言:javascript
复制
<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>

我将click事件处理程序设置为:

代码语言:javascript
复制
private void Context_Delete(object sender, System.EventArgs e)  { }

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

EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2013-05-30 05:40:30

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

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

代码语言:javascript
复制
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);
}
票数 39
EN

Stack Overflow用户

发布于 2013-05-30 05:01:09

通常,您不处理行(如果您这样做了-再考虑一下原因)-而是使用视图模型。当您打开上下文菜单时,您将选中您的项目,因此可以通过DataGrid.SelectedItem属性访问它。然而,如果你真的需要DataGridRow -你有你的DataGrid.SelectedIndex,这里有很多关于如何获得行的答案。像Get row in datagrid一样

票数 7
EN

Stack Overflow用户

发布于 2014-12-19 01:22:39

为了通过一个例子扩展morincer的观点,我最终使用了一种更简单的方法……

代码语言:javascript
复制
 private void MenuItem_OnClickRemoveSource(object sender, RoutedEventArgs e)
 {
     if (SourceDataGrid.SelectedItem == null) return;  //safety first

     _importViewModel.SourceList.Remove((SourceFileInfo)SourceDataGrid.SelectedItem);
 }

在我的例子中,

代码语言:javascript
复制
_importViewModel.SourceList 

是行绑定到的ObservableCollection。因此,根据最佳实践,我只需从集合中删除所选的项,然后绑定就会处理UI。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16822956

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档