开发者

How to add a ContextMenu depending on which WPF DataGrid row is right-clicked?

I need to display different options in a ContextMenu depending on which row of a WPF DataGrid is right-clicked. My initial ideas were to accomplish this through either binding or handling a mouse click event, but I haven't had success with either strategy so far. Any help would be most ap开发者_运维百科preciated!

Thank you!

Denise


You can handle the DataGrid's ContextMenuOpening event and based on the original source of the routed event you adjust your context menu.

Below is a sample where I show a context menu if the data context of the original source is of type Inventory otherwise I do not show the context menu by handling the event.

Private Sub InventoriesDataGrid_ContextMenuOpening( _
    ByVal sender As Object, _
    ByVal e As System.Windows.Controls.ContextMenuEventArgs) Handles _
    InventoriesDataGrid.ContextMenuOpening

    Dim context = DirectCast(e.OriginalSource, System.Windows.FrameworkElement).DataContext

    If TypeOf context Is Inventory Then
        InventoriesDataGrid.ContextMenu = InventoriesDataGrid.Resources("DefaultContextMenu")
    Else
        e.Handled = True 'Do not show context menu.
    End If
End Sub

I'm sure it is too late to help you now, but in case it is not too late and for anyone else who comes across this.


You can try the OriginalSource from the ContextMenuEventArgs argument in the ContextMenuOpening event :

DataGridResults.ContextMenuOpening += (sender, args) =>
{
    var frameworkElement = args.OriginalSource as FrameworkElement;
    var gridRow = frameworkElement != null ? frameworkElement.TemplatedParent as DataGridRow : null;
}

Note however that the use of TemplatedParent depends on how the datagrid items were bound

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜