Get Grid Row# from ContextMenu Action

2020-05-07 08:10发布

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 can get the grid back but I cannot get the Row which the click occurred.

  • I do not know what UIElement is being clicked on as I want the user to be able to click on any element within the row boundaries.

Here is what I have already,

<Grid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Open Client CP" Background="#FF1C1C1C"/>
                    <MenuItem Header="Auto Mine" Background="#FF1C1C1C"/>
                    <MenuItem Header="Disconnect" Background="#FF1C1C1C"/>
                    <MenuItem Header="Uninstall" Background="#FF1C1C1C"/>
                    <MenuItem Header="Refresh" Background="#FF1C1C1C" Click="onRefreshMenuClick" CommandParameter="{Binding RelativeSource={RelativeSource Self}, Path=Parent}"/>
                </ContextMenu>
            </Grid.ContextMenu>


 private void onRefreshMenuClick(object sender, RoutedEventArgs e)
    {
        MenuItem mi = sender as MenuItem;
        if (mi != null)
        {
            ContextMenu cm = mi.CommandParameter as ContextMenu;
            if (cm != null)
            {
                Grid g = cm.PlacementTarget as Grid;
                if (g != null)
                {
// need something here like g.getrowof(cm.placementtarget)
                    if (debugWindow != null)
                        debugWindow.LogTextBox.AppendText("Requested refresh from "+ row);
                }
            }
        }
    }

2条回答
你好瞎i
2楼-- · 2020-05-07 08:39

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....
}
查看更多
虎瘦雄心在
3楼-- · 2020-05-07 08:46

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)

查看更多
登录 后发表回答