我正在尝试从后面的代码中模拟右键单击,如下所示:
static void RightMouseClick(Visual visual)
{
UIElement uel = (UIElement)visual;
var e = new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Right);
e.RoutedEvent = Mouse.MouseDownEvent;
uel.RaiseEvent(e);
Thread.Sleep(100);
e.RoutedEvent = Mouse.MouseUpEvent;
uel.RaiseEvent(e);
}
我希望 ContextMenu 能够在我的控件上弹出,但这并没有发生。似乎右键单击可以工作,但上下文菜单没有出现。
我成功地初始化了自己的上下文菜单并打开它。例如,我在
Grid
初始化时执行此代码:
private void Grid_Initialized(object sender, EventArgs e)
{
var contextMenu = new ContextMenu();
var mi = new MenuItem();
mi.Header = "File";
var mia = new MenuItem();
mia.Header = "New";
mi.Items.Add(mia);
var mib = new MenuItem();
mib.Header = "Open";
mi.Items.Add(mib);
var mib1 = new MenuItem();
mib1.Header = "Recently Opened";
mib.Items.Add(mib1);
var mib1a = new MenuItem();
mib1a.Header = "Text.xaml";
mib1.Items.Add(mib1a);
contextMenu.Items.Add(mi);
contextMenu.IsOpen = true;
var ctrl = (FrameworkElement)sender;
ctrl.ContextMenu = contextMenu;
}