从上下文菜单操作中获取网格行号

Get Grid Row# from ContextMenu Action

我在网格的每个 RowDefinition 中得到了一个带有 System.Windows.Controls.Image 和标签等控件的网格。问题是当我右键单击上下文菜单时它可以工作并且我可以取回网格但我无法获取发生点击的行。

这是我已有的,

<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);
                }
            }
        }
    }

您可以点击测试 DataGridRow,给定鼠标位置和网格。

// 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(可视层命中测试)

也许是这样的?:

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....
}