【发布时间】:2021-12-19 11:27:34
【问题描述】:
在 WinUI 3 应用程序中,我使用来自 CommunityToolkit.WinUI.UI.Controls 命名空间的 DataGrid,请参阅 MSDN DataGrid class。
我正在寻找一种方法来获取当前选择或点击的DataGridCell 的实例。
我需要这个,因为我想在用户选择/单击某个单元格时显示MenuFlyout(MenuFlyout 控件就像一个小弹出窗口,请参阅MSDN MenuFlyout)。此弹出按钮应显示在单元格旁边。为此,MenuFlyout 类有一个可用的ShowAt 方法,它接受FrameworkElement 类型的参数(“用作浮出控件放置目标的元素。”)。我想将当前选中的单元格传递给这个方法。
这是我当前的代码:
private void MyDataGrid_CurrentCellChanged(object sender, System.EventArgs e)
{
MenuFlyout flyout = new MenuFlyout();
MenuFlyoutItem item = new MenuFlyoutItem();
item.Text = "Test";
flyout.Items.Add(item);
// How do I get an instance of the currently selected cell in the DataGrid?
FrameworkElement theCurrentlySelectedCell = ?;
flyout.ShowAt(theCurrentlySelectedCell);
}
问题是我不知道如何获取 DataGrid 当前选择/单击的单元格的实例。我在DataGrid 类中找不到任何对我有帮助的东西。
不幸的是,我在上面的代码示例中使用的CurrentCellChanged 事件在其事件参数中也没有此信息,它只有一个e 类型的EventArgs 参数。在这种情况下,sender 是 DataGrid,而不是单元格。
我发现DataGrid 上有一个CurrentColumn 属性,请参阅MSDN DataGrid CurrentColumn。但我无法从这个实例到行的DataGridCell 实例。
有谁知道如何获取当前选中或点击的DataGridCell的实例?
【问题讨论】:
-
您检查过 SelectionChanged 事件吗?也许它更适合您的需求,因为它提供了一个 SelectionChangedEventArgs。
-
不幸的是,这对我没有帮助。 SelectionChangedEventArgs 包含一个“AddedItems”属性,但这仅包含绑定到每一行的数据对象的实例,或者更准确地说是绑定到现在选择的行。 “OriginalSource”属性始终为空。
标签: c# user-interface windows-community-toolkit winui-3