C# WPF上下文菜单关闭事件,如何区分关闭方法
在我的画布中,我有一个ContextMenu,当您在菜单中选择一个选项时,或者当您在菜单外单击时,它具有预期的关闭功能。但是,我希望我的程序根据关闭ContextMenu时使用的方法做出不同的响应。据我所知,ContextMenu上的Closed事件在两种情况下都会触发。有什么办法可以区分这一点吗?您能详细解释一下这个问题吗? 我认为很明显,你必须这样做。1:单击您创建的ContexMenu选项,该选项将调用一个事件,并在其外部单击,从而取消关联菜单。顺便说一句,我是根据我对你问题的理解来回答的。如果我弄错了,请告诉我 下面的代码只是一个演示代码,它背后的逻辑很重要C# WPF上下文菜单关闭事件,如何区分关闭方法,c#,wpf,contextmenu,C#,Wpf,Contextmenu,在我的画布中,我有一个ContextMenu,当您在菜单中选择一个选项时,或者当您在菜单外单击时,它具有预期的关闭功能。但是,我希望我的程序根据关闭ContextMenu时使用的方法做出不同的响应。据我所知,ContextMenu上的Closed事件在两种情况下都会触发。有什么办法可以区分这一点吗?您能详细解释一下这个问题吗? 我认为很明显,你必须这样做。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;
}
}
祝你一切顺利,海达