private void datagrid_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
object item = GetElementFromPoint((ItemsControl)sender, e.GetPosition((ItemsControl)sender));
}
private object GetElementFromPoint(ItemsControl itemsControl, Point point)
{
UIElement element = itemsControl.InputHitTest(point) as UIElement;
while (element != null)
{
if (element == itemsControl)
return null;
object item = itemsControl.ItemContainerGenerator.ItemFromContainer(element);
if (!item.Equals(DependencyProperty.UnsetValue))
return item;
element = (UIElement)VisualTreeHelper.GetParent(element);
}
return null;
}
可以实现根据选中datagrid中对象属性的不同弹出不同的右键菜单:
if(item.type=="文件")
{
ContextMenu textmenu = new ContextMenu();
MenuItem item = new MenuItem();
item .Header = "剪切";
ClearText.Click += new RoutedEventHandler(btnCut_Click);
datagrid.ContextMenu = textmenu;}
else if(item.type=="文件夹")
{……}