views:

94

answers:

2

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 something.

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!

A: 

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.

AlishahNovin
+2  A: 

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.

Ray Burns