Quick tip: How to open popup or ContextMenu in XBAP application

If you want to use ContextMenu in XBAP application this will work, only if your XBAP is in full trust mode. Else you’ll get "Request for the permission of type ‘System.Security.Permissions.UIPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089′ failed". But even with Full Trust application, if you’ll try to open context menu explicitly it wont. The error, you’ll get will be "Cannot create a top-level child window". This is right. You cannot use layered windows without explicitely set parent inside browser sandbox.

Why this happens? Honestly, as for me, this is bug inside System.Windows.Controls.PopupControlService internal class (tnx to Shared .NET source code). For some reason PopupControlService set parent of the context menu while it raises ToolTipOpenning event. More, then this, it uses internal dependency property OwnerProperty to do it. So pity.

_currentToolTip.SetValue(OwnerProperty, o);

And if it is not enough it probably has memory leak, I described earlier.

_currentToolTip.Closed += OnToolTipClosed;
private void OnToolTipClosed(object sender, EventArgs e)
        {
            ToolTip toolTip = (ToolTip)sender;
            toolTip.Closed -= OnToolTipClosed;

Never mind. The question is how to take care on it, when we have no public Owner property and Parent is read only? Fortunately, dev team leave us PlacementTarget property to explicitly set the owner of ContextMenu. So, all you have to do is to add one line before setting IsOpen property to true.

private void OnMouseDown(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                contextMenu.PlacementTarget = sender as UIElement;
                contextMenu.IsOpen = true;
            }
        }

 

That’s all, folks. Now you can safely open ContextMenu in XBAP application not only with right, but also with Left mouse button as well as with keyboard event or any other code you want to.

Have a nice day.

  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • DotNetKicks
  • DZone
  • Live
  • Reddit
  • TwitThis
  • email
  • Slashdot
  • StumbleUpon

You may also be interested with:

  1. Real singleton approach in WPF application
  2. Quick IT tip: How to build bootable USB stick
  3. INotifyPropertyChanged auto wiring or how to get rid of redundant code

No comments yet

Leave a Reply

Recommended

 


Sponsor


Partners

WPF Disciples
Dreamhost
Code Project
Switched to Better Place

Together