简体   繁体   中英

Executing code on ContextMenu open in WPF MVVM

To control a popup window in WPF, I usually have an IsPopupOpen property on my ViewModel which is bound to the IsOpen property of the PopUp in the XAML. When the user then presses a button to open the popup, in the button's action code, I can set IsPopupOpen to true and the popup appears.

I am trying to do the same thing now with a ContextMenu so I can close it programatically. It also has an IsOpen property I can bind to and should, theoretically, work the same way.

However, with the ContextMenu we get the opening function for "free" on right click - it's just built in to the object. So I have no command to bind to in order to execute code which sets the initial IsPopupOpen value to true. Therefore IsPopupOpen starts as false and stays as false and the ContextMenu never appears when the user right-clicks.

There doesn't seem to be anything I can bind a Command to in the ContextMenu to make this work, so I'm slightly lost as to how to proceed. I have tried setting the Binding mode for IsOpen on the ContextMenu to TwoWay to see if it would set to true on open, but that doesn't seem to work.

Is there any way round this, or another approach I can try?

Have a look at FrameworkElement.ContextMenuOpening Event at https://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.contextmenuopening(v=vs.110).aspx and do check the Remarks section.

And check this one also How to: Handle the ContextMenuOpening Event at https://msdn.microsoft.com/library/bb613568(v=vs.100).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM