从ContextMenu获取Grid *的Row#

时间:2015-01-03 22:21:17

标签: c# wpf

我在Grid的每个RowDefinition中都有一个带有控件的Grid,例如System.Windows.Controls.Image和Labels。问题是,当我做右键单击contextmenu它工作,我可以得到网格,但我不能得到点击发生的行。

  • 我不知道点击什么是UIElement,因为我希望用户能够点击行边界内的任何元素。

顺便说一句,我使用的是Grid而不是DataGrid!

这是我已经拥有的,

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

1 个答案:

答案 0 :(得分:0)

您可以在此post中找到解决方案。下面我根据你的问题调整解决方案:

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)
                    var point = Mouse.GetPosition(g);

                    int row = 0;
                    int col = 0;
                    double accumulatedHeight = 0.0;
                    double accumulatedWidth = 0.0;

                    // calc row mouse was over
                    foreach (var rowDefinition in g.RowDefinitions)
                    {
                        accumulatedHeight += rowDefinition.ActualHeight;
                        if (accumulatedHeight >= point.Y)
                            break;
                        row++;
                    }

                    // calc col mouse was over
                    foreach (var columnDefinition in g.ColumnDefinitions)
                    {
                        accumulatedWidth += columnDefinition.ActualWidth;
                        if (accumulatedWidth >= point.X)
                            break;
                        col++;
                    }
                } 
            }
        }   
 }