views:

424

answers:

1

Hello guys! I need to have different context menus in my datagrid - one for its header and one for rows of a grid. So I'm handling MouseClick event and than I need to evaluate if the underlying object for mouse cursor is Datagrid's header. Can you explain me how can I make this? The thing that I can't understand is that neither of DataGrid's and DataGridColumn's hierarchy of objects contain DataGridColumnHeader object or any reference to it. But in virtual tree if I get textblock that is located in header and contains column header's text and then get it parent container, I'll get DatagridColumnHeader object.

Any help is appreciated. Thanks in advance!

A: 
Private Sub DGrid_MouseLeftButtonDown(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs)
    Dim dep As DependencyObject = DirectCast(e.OriginalSource, DependencyObject)

    ' iteratively traverse the visual tree 
    While (dep IsNot Nothing) AndAlso Not (TypeOf dep Is DataGridRow OrElse TypeOf dep Is Primitives.DataGridColumnHeader OrElse TypeOf dep Is DataGrid)
        dep = VisualTreeHelper.GetParent(dep)
    End While

    If dep Is Nothing Then
        Exit Sub
    End If

    If TypeOf dep Is Primitives.DataGridColumnHeader Then
        Dim CurrentHeader As Primitives.DataGridColumnHeader = TryCast(dep, Primitives.DataGridColumnHeader)
        If Not CurrentHeader Is Nothing Then
            CurrentHeader.ContextMenu.Items.Add("Option")
        End If
    ElseIf TypeOf dep Is DataGridRow Then
        'Something else
    End If
End Sub