0

I Have a DataGrid and I'd like to open a context Menu on rightclick, and filter it in base of a property of the selected item.

The problem is that with "fileGrid_MouseRightButtonUp" the selected item isnot the one under the cursor, but the previeouly selected one.

So how can i select the item of the datagrid on rightclick?

Its WPF im talking about

The piece of code:

        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 Answers2

1

Try something like this,

    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.
    }
nikhil
  • 1,578
  • 3
  • 23
  • 52
0

Based on this article, you can use

    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
        }
    }
rmojab63
  • 3,513
  • 1
  • 15
  • 28