开发者

How can I force a ContextMenu to close (WPF project)?

I have a ListBox with items, and have assigned a ContextMenu to it with three menu items. Everything is working fine except that one of the menu items launches a lengthy operation. I would like to close the ContextMenu from the handler, and maybe display an hour-glass cursor or s开发者_C百科omething.

Can that be done? Or, should I be using a Popup instead? If so, how do I use a Popup in lieu of a ContextMenu? My assumption is I would have to manage it completely - placement and lifetime.

Thanks!


What you want is:

myContextMenu.IsOpen = false;

Be sure to call this before your lengthy operation occurs. Depending on your operation, you may want to consider making it asynchronous by performing the operation on another thread - that way, you won't halt the application thread.


You can simply run your lengthly operation under Dispatcher.BeginInvoke:

private void OnSomeContextMenuCommand(object sender, EventArgs e)
{
  Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
  {
    // Put long-running operation here
  }));
}

If you do this, the ContextMenu will close before your long-running operation begins.

In general I prefer this solution to explicitly closing the ContextMenu because it completely separates the UI from the command handling.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜