WPF DataGrid SelectItem BeforeRightClick

WPF DataGrid SelectItem BeforeRightClick

我有一个 DataGrid,我想在右键单击时打开一个上下文菜单,并在 selected 项目的 属性 的基础上过滤它。

问题是 "fileGrid_MouseRightButtonUp" 的 selected 项目不是光标下的项目,而是之前 selected 的项目。

那么我如何 select 右键单击​​数据网格的项目?

我说的是 WPF

代码段:

        private void fileGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (fileGrid.SelectedItems.Count != 0)
        {
            if(fileGrid.SelectedItems.Count == 1 && !(fileGrid.SelectedItem as FileD).EsAudio)
            {
                cMenu.Items.Filter = item =>
                {
                    var it = item as MenuItem;
                    return it.Header.ToString() != "ConvertToAudio";
                };
            }
            else
            {
                cMenu.Items.Filter = item =>
                {
                    return true;
                };
            }
        }
    }

尝试这样的事情,

    private void fileGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        foreach (var item in fileGrid.Rows)
                    {
                        if (item.IsMouseOver)
                        {
                            fileGrid.SelectedIndex = item.Index;
                            break;
                        }
                    }
//Then do what you want to do.
    }

基于this article,您可以使用

    private void DataGrid_MouseRightButtonUp(object sender, MouseButtonEventArgs e)
    {
        DependencyObject dep = (DependencyObject)e.OriginalSource;

        // iteratively traverse the visual tree
        while ((dep != null) && !(dep is DataGridCell) && !(dep is DataGridColumnHeader))
        {
            dep = VisualTreeHelper.GetParent(dep);
        }

        if (dep == null)
            return;

        if (dep is DataGridColumnHeader)
        {
            DataGridColumnHeader columnHeader = dep as DataGridColumnHeader;
            // do something
        }

        if (dep is DataGridCell)
        {
            DataGridCell cell = dep as DataGridCell;
            // do something
        }
    }