I've recently taken over the documentation for some of the Silverlight controls, and one of the controls I now own is Popup. One of the first things I do when preparing to document a control is play around with it in code. Using the Popup control is pretty straightforward, but I wanted to share the basics, particularly since we didn't get the documentation in for Beta1 (see Margaret's post; we are a bit understaffed) Popup is useful for hosting content, particularly a UserControl, in a new "popup" on top of the existing Silverlight content.
To get started, I created a Silverlight application project and added a user control named MyControl to the project.
Following is the code for my user control. It's a control that contains a button which, when clicked, causes the pop-up to disappear. (It's basic--I don't want to detract from the main point of this post). First the code in MyControl.xaml:
<Border BorderThickness="5" BorderBrush="Black">
<StackPanel x:Name="LayoutRoot" Background="White">
<TextBlock Margin="5" Text="See the popup?" />
<Button Width=" 50" Content="Yes" Click="Button_Click"/>
Here's the click event handler for MyControl.xaml.cs. The event-handler simply sets the Visibility property to Visibility.Collapsed, to remove it from the layout.
private void Button_Click(object sender, RoutedEventArgs e)
// Remove the control from the layout.
this.Visibility = Visibility.Collapsed;
Next I'll add a button to Page.xaml for my main Silverlight control, which when clicked, shows my user control. Paste this into the existing Grid in Page.xaml:
<Button Width="100" Height="50" x:Name="showPopup" Click="showPopup_Click"
Content="Show Popup" />
My next task is to handle the click event for the ShowPopup button. I'll need to add a using statement for System.Windows.Controls.Primitives to Page.xaml.cs, because Popup is in the Primitives namespace:
Now I need to handle the Click event and show my user control. I'll create a new Popup object and set its Child property to my user control. I can optionally tweak where the popup shows up on the screen with VerticalOffset and HorizontalOffset. Finally, I'll show the popup by setting its IsOpen property to true.
// Declare the popup object.
private void showPopup_Click(object sender, RoutedEventArgs e)
// Create a popup.
p = new Popup();
// Set the Child property of Popup to an instance of MyControl.
p.Child = new MyControl();
// Set where the popup will show up on the screen.
p.VerticalOffset = 200;
p.HorizontalOffset = 200;
// Open the popup.
p.IsOpen = true;
That's all there is to it. When you run the sample, you can click the button to show the popup. When you click the popup button, the popup disappears. --Cheryl
That's all there is to it. When you run the sample, you can click the button to show the popup. When you click the popup button, the popup disappears.