Creating popup windows in XBAP applications

A colleague at DevelopMentor recently asked me about creating popup windows in XAML browser applications (XBAP). Normally this is not allowed – if you try to create a top-level window you will get a SecurityException because WPF asks for UIPermission which is strictly prohibited when hosted in the browser.

It turns out, however, that you can get a popup window – there’s a hidden little gem in the System.Windows.Controls.Primitive namespace that is your friend: Popup.

It’s the same underlying class that ToolTip, Menu, and ComboBox use to display drop-down menus and overlays and it is browser-hosting aware! It’s pretty limited in functionality – I’m not sure you can get it to move around with the mouse for example, but for simple cases it works great. Here’s a code snippet – wire this up to a button in an XBAP:

   1: void OnClick(object sender, EventArgs e)
   2: {
   3:    Popup window = new Popup();
   5:    StackPanel sp = new StackPanel { Margin = new Thickness(5) };
   6:    sp.Children.Add(new TextBlock { Text = "Hi from a popup" });
   7:    Button newButton = new Button { Content = "Another button" };
   8:    newButton.Click += delegate { window.IsOpen = false; };
   9:    sp.Children.Add(newButton);
  10:    sp.Children.Add(new Slider { Minimum = 0, Maximum = 50, Value = 25, Width = 100 });
  12:    window.Child = new Border { Background = Brushes.White, BorderBrush = Brushes.Black, 
BorderThickness = new Thickness(2), Child = sp };
  13:    window.PlacementTarget = this;
  14:    window.Placement = PlacementMode.Center;
  16:    window.IsOpen = true;
  17: }

The key thing you need to do is set the PlacementTarget. That associates a “parent” window and without it, the Popup class asserts UIPermission which will fail in the browser environment.

About Mark Smith

Windows systems developer with low-level operating system, threading and .NET experience. For the past several years I have been involved with WPF/Silverlight and most recently iOS and Android. I have worked as an architect and designer for several companies and am particularly interested in client/server and graphical solutions. Specialties:.NET, WPF, Silverlight, Windows, iOS

Latest Blog Posts

Building Windows Store apps with HTML/JS and WinJS

Thanks to everyone who attended the WinJS marathon! Here's the slides and demos we … Read More »

NumericTextBoxBehavior for XAML-based Windows Store Applications

One of the first (and arguably most useful) behaviors that I wrote for MVVMHelpers was a … Read More »