WPF DataGrid SelectItem BeforeRightClick

时间:2017-02-15 22:25:29

标签: c# wpf datagrid right-click

我有一个DataGrid,我想在右键单击打开一个上下文菜单,并根据所选项目的属性过滤它。

问题在于" fileGrid_MouseRightButtonUp"所选项目不是光标下的项目,而是前面选择的项目。

那么如何在右键单击中选择datagrid的项目?

它的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;
                };
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

尝试这样的事情,

    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.
    }

答案 1 :(得分:0)

基于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
        }
    }