如何知道何时单击 DataGridRow?

How to know when a DataGridRow is clicked?

我正在使用 the Windows Community Toolkit WinUI DataGrid control。单击一行时,我想 运行 一些代码。我该怎么做?

我试过:

有什么想法吗?

我最终使用了 PointerReleased 事件。 (之前我已经放弃了这个事件,因为我无法弄清楚点击了哪一行。)

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

为了找到被点击的 DataGridRow,我遍历了可视化树:

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

不是最优雅的解决方案,但它有效:)