Get Grid Row# from ContextMenu Action

后端 未结 2 1688
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 17:04

I got a Grid with controls such System.Windows.Controls.Image and Labels in each RowDefinition of my Grid. The problem is when I do the right click contextmenu it works and I ca

相关标签:
2条回答
  • 2021-01-28 17:39

    You can hit test for DataGridRow, given mouse position & the Grid.

    // Retrieve the coordinate of the mouse position.
    Point pt = e.GetPosition((UIElement)sender);
    
    DataGridRow row = null;
    
    // Set up a callback to receive the hit test result enumeration.
    VisualTreeHelper.HitTest(myGrid, null,
        new HitTestResultCallback(res => {
           row = res.VisualHit as DataGridRow;
           return row != null ? HitTestResultBehavior.Stop :
             HitTestResultBehavior.Continue;
        }),
        new PointHitTestParameters(pt));
    

    http://msdn.microsoft.com/en-us/library/ms752097.aspx (Hit Testing in the Visual Layer)

    0 讨论(0)
  • 2021-01-28 17:46

    maybe something like this?:

    private void DoStuff(object sender, RoutedEventArgs e)
    {
        // Get the selected MenuItem
        var menuItem = (MenuItem)sender;
    
        // Get the ContextMenu for the menuItem
        var ctxtMenu = (ContextMenu)menuItem.Parent;
    
        // Get the placementTarget of the ContextMenu
        var item = (DataGrid)ctxtMenu.PlacementTarget;
    
        // Now you can get selected item/cell etc.. and cast it to your object
        // example: 
        //var someObject = (SomeObject)item.SelectedCells[0].Item;
    
        // rest of code....
    }
    
    0 讨论(0)
提交回复
热议问题