WPF 上下文菜单关闭事件,如何区分关闭方法



在我的画布中,我有一个上下文菜单,当您在菜单中选择一个选项或单击外部时,它具有关闭的预期功能。但是,我希望我的程序根据使用这些方法来关闭上下文菜单的方法做出不同的响应。据我所知,上下文菜单上的已关闭事件在两种情况下都会触发。有什么办法可以区分吗?

你能解释更多关于问题的信息吗? 我认为很明显,你必须设想。1:单击您创建的ContexMenu选项,该选项将调用一个事件,然后单击外部将取消上下文菜单。顺便说一下,我根据我对你问题的理解做出了回答。如果我弄错了,请告诉我。

波纹管代码只是一个演示代码,背后的逻辑很重要。

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
// Windows Load event
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
// Very Important Because by default it's null
this.ContextMenu = new ContextMenu();
// Making 3 sample Menu Item for ContextMenu
MenuItem firstMenuItem = new MenuItem()
{
Header = "FirsMenu"
};
//1st of three way to give event to Controls. 
// Giving click Event to firstMenuItem to seprate it's click behavior from Other Menu Items
firstMenuItem.Click += (s, e) =>
{
// if Tag be Null on context Menu closing it's get that non of item selected so the click must be out side or lost focused
this.ContextMenu.Tag = 1;
MessageBox.Show("First Menu Clicked");
};
MenuItem secondMenuItem = new MenuItem()
{
Header = "SecondMenu"
};
//2nd of three way to give event to Controls. 
// Giving click Event to secondMenuItem to seprate it's click behavior from Other Menu Items
secondMenuItem.Click += delegate
{
// if Tag be Null on context Menu closing it's get that non of item selected so the click must be out side or lost focused
this.ContextMenu.Tag = 1;
MessageBox.Show("Second Menu Clicked");
};
MenuItem thirdMenuItem = new MenuItem()
{
Header = "ThirdMenu"
};
//3rd of three way to give event to Controls. 
// Giving click Event to thirdMenuItem to seprate it's click behavior from Other Menu Items
thirdMenuItem.Click += ThirdMenuOnClick;
this.ContextMenu.Items.Add(firstMenuItem);
this.ContextMenu.Items.Add(secondMenuItem);
this.ContextMenu.Items.Add(thirdMenuItem);
this.ContextMenu.Closed += ContextMenuOnClosed;
}
private void ThirdMenuOnClick(object sender, RoutedEventArgs e)
{
// if Tag be Null on context Menu closing it's get that non of item selected so the click must be out side or lost focused
this.ContextMenu.Tag = 1;
MessageBox.Show("Third Menu Clicked");
}
// Event for opening contextmenu on right mouse button click 
private void MainWindow_OnMouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
this.ContextMenu.IsOpen = true;
}
private void ContextMenuOnClosed(object sender, RoutedEventArgs e)
{
// if null means click must be out side or lost focused
if (((ContextMenu)sender).Tag == null)
{
MessageBox.Show("You Clicked OutSide");
}
// very Importnt code , because it will reset the context menu tag logically
((ContextMenu)sender).Tag = null;
}
}

祝你一切顺利,海达尔。

相关内容