我在Grid的每个RowDefinition中都有一个带有控件的Grid,例如System.Windows.Controls.Image和Labels。问题是,当我做右键单击contextmenu它工作,我可以得到网格,但我不能得到点击发生的行。
这是我已经拥有的,
<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);
}
}
}
}
答案 0 :(得分:0)
你可以点击DataGridRow
的测试,给定鼠标位置&amp;网格。
// 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(在视觉层中命中测试)
答案 1 :(得分:0)
也许是这样的?:
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....
}