【问题标题】:How to know when a DataGridRow is clicked?如何知道何时单击 DataGridRow?
【发布时间】:2022-01-22 12:55:07
【问题描述】:

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

我试过了:

  • SelectionChanged 事件:仅在第一次单击该行时有效,之后将选择同一行。如果通过键盘移动该行,也会触发。
  • CurrentCellChanged 事件:仅在第一次单击单元格时有效,因为在此之后单击同一单元格不会更改当前单元格。 (而且我找不到以编程方式清除当前单元格的方法。)
  • Answers like this 展示了如何在 WPF 中通过样式添加行事件处理程序,但这在 WinUI 中不起作用。

有什么想法吗?

【问题讨论】:

    标签: c# xaml datagrid windows-community-toolkit winui-3


    【解决方案1】:

    我最终使用了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;
    }
    

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

    【讨论】:

      猜你喜欢
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      • 2021-12-29
      • 2021-08-27
      • 1970-01-01
      相关资源
      最近更新 更多