Search code examples
c#xamldatagridwindows-community-toolkitwinui-3

How to know when a DataGridRow is clicked?


I am using the Windows Community Toolkit WinUI DataGrid control. I would like to run some code when a row is clicked. How can I do that?

I have tried:

  • SelectionChanged event: Only works the first time the row is clicked, as after that the same row is being selected. Also gets triggered if the row is moved to via the keyboard.
  • CurrentCellChanged event: Only works the first time a cell is clicked, as after that clicking the same cell does not change the current cell. (And I could not find a way to clear the current cell programmatically.)
  • Answers like this show how to add row event handlers via style in WPF, but this does not work in WinUI.

Any ideas?


Solution

  • I ended up using the PointerReleased event. (Previously I had discarded this event as I could not figure out which row was clicked.)

    <ctWinUI:DataGrid
        PointerReleased="dgDesktops_PointerReleased"
        ...>
    

    And to find the DataGridRow that was clicked I traverse the visual tree:

    private async void dgDesktops_PointerReleased(object sender, PointerRoutedEventArgs e)
    {
        DataGridRow clickedRow = ViewUtils.FindParent<DataGridRow>((UIElement)e.OriginalSource);
        if (clickedRow != null)
        {
            MyModel rowModel = (MyModel)clickedRow.DataContext;
            // Do stuff
        }
    }
    
    public static T FindParent<T>(DependencyObject childElement) where T : Control
    {
        DependencyObject currentElement = childElement;
    
        while (currentElement != null)
        {
            if (currentElement is T matchingElement)
            {
                return matchingElement;
            }
    
            currentElement = VisualTreeHelper.GetParent(currentElement);
        }
    
        return null;
    }
    

    Not the most elegant solution, but it works :)