Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
1285
Select row on right click
posted

My grid has a context menu.  I would like when a user right clicks on a row that, that row gets selected and then I can put in menu items that pertain to a row rather then the grid.  And when user chooses a menu item I know what row to do that function on.

Any ideas?

Thanks,

Rick

  • 2677
    posted

    Hey Rick,

    If all you want to do is find the Record you clicked on and select it, here is a simple solution.  All you have to do is handle the mouserightbuttondown event and get the original source from the mouse down.  Then, use the VisualTreeHelper class to navigate up the parent chain to find the DataRecordCellArea that contains the element you clicked on.  Here is the code.

    private void XamGrid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
            {
                DependencyObject dobj = (DependencyObject)e.OriginalSource;
                DependencyObject parentElement = VisualTreeHelper.GetParent(dobj);

                while (parentElement != null)
                {
                    if (parentElement is DataRecordCellArea)
                    {
                        Record r = ((DataRecordCellArea)parentElement).Record;
                        if (r.RecordType == RecordType.DataRecord)
                        {
                            r.IsActive = true;
                            //r.IsSelected = true;
                        }
                        break;
                    }
                    parentElement = VisualTreeHelper.GetParent(parentElement);
                }
            }

    A few side notes:

    If you want to be able to click on the record selector of the row, you can replace DataRecordCellArea with DataRecordPresenter.

    You will notice that I used the IsActive rather then IsSelected.  You can use either one but keep in mind the default selection of rows is multi select so you will have to either make that single or clear the selected records collection each time.  I think IsActive is better anyway. 

    Also, if you will be dealing with a hierarchical grid or a grouped grid, you will have to add support for those record types.  I only used DataRecord.  Hope this helps.