UWP:DataGrid、MenuFlyout 右键单击

标签 uwp datagrid xamarin.uwp windows-community-toolkit

问题: 右键单击一行时,我正在尝试在 DataGrid 上创建一个菜单。

目标: 右键单击一行时是否可以在 DataGrid 上创建菜单;我可以在单元格上创建一个吗?

<controls:DataGridTemplateColumn Header="OrderId">
    <controls:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ContextFlyout>
                    <MenuFlyout>
                        <MenuFlyoutItem Text="Copy" Icon="Copy" Click="MenuFlyoutItem_Copy" />
                        <MenuFlyoutSeparator />
                        <MenuFlyoutItem Text="Delete" Icon="Delete" Click="MenuFlyoutItem_Delete" />
                    </MenuFlyout>
                </Grid.ContextFlyout>
                <TextBlock Text="{Binding OrderId}" />
            </Grid>
        </DataTemplate>
    </controls:DataGridTemplateColumn.CellTemplate>
</controls:DataGridTemplateColumn>

private void MenuFlyoutItem_Copy(object sender, RoutedEventArgs e)
{
    ObservableCollection<SampleOrder> dataGrid = DataGrid.ItemsSource as ObservableCollection<SampleOrder>;

    MenuFlyoutItem mfi = sender as MenuFlyoutItem;
    SampleOrder seleted = mfi.DataContext as SampleOrder;

    var copiedItem = (SampleOrder)seleted.Clone();

    dataGrid.Add(copiedItem);
}

private void MenuFlyoutItem_Delete(object sender, RoutedEventArgs e)
{
    ObservableCollection<SampleOrder> dataGrid = DataGrid.ItemsSource as ObservableCollection<SampleOrder>;

    MenuFlyoutItem mfi = sender as MenuFlyoutItem;
    SampleOrder seleted = mfi.DataContext as SampleOrder;

    dataGrid.Remove(seleted);
}

最佳答案

除非我遗漏了什么,否则这比 Nico 的回答要容易得多。您需要做的就是像这样设置 RowStyle 属性:

<controls:DataGrid.RowStyle>
    <Style TargetType="controls:DataGridRow">
        <Setter Property="controls:DataGridRow.ContextFlyout">
            <Setter.Value>
                <MenuFlyout>
                    <MenuFlyoutItem x:Name="MyMenuItem"
                                    Click="MyMenuItem_Click"
                                    Text="Do Things" />
                </MenuFlyout>
            </Setter.Value>
        </Setter>
    </Style>
</controls:DataGrid.RowStyle>

然后在你的处理程序中:

private void MyMenuItem_Click(object sender, RoutedEventArgs e)
{
    var item = (sender as FrameworkElement).DataContext as MyModel;
    // Do things with your item.
}

关于UWP:DataGrid、MenuFlyout 右键单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54769413/

相关文章:

c# - 防止在 DataGrid 中按下回车键时自动更改行

xamarin.android - Xamarin.Forms(UWP、Droid 和 iOS)的 Breeze#?

c# - Xamarin.Forms UWP 应用程序在运行时使用 .net native 工具链失败,但可以正常工作

xamarin - 如何在 Xamarin Forms 中以适当的图像比例在 UWP 中设置 SpashScreen?

c# - UWP在启动时启动后台任务

c# - 为什么合成动画(UWP 文档中的示例)不起作用?

c# - WPF - 更改数据绑定(bind) DataGrid 上的列名

wpf datagrid 复制并粘贴您所看到的内容

uwp - 在 C++/WinRT 项目中使用 CoreDispatcher::RunAsync 时,在定义之前无法使用获取 "a function that returns ' auto'

events - 如何收听 UWP Xaml Slider 操作开始/结束事件?