Running on Empty

The few things I know, I like to share.

WPF Popup control. (Part 1, the Quick and Dirty Way)

Introduction

One of my favorite features in WPF is the separation of functionality and display of visuals in the UI.  So I thought I would start a new series demonstrating some cool features I have used in WPF, starting with Popup controls.

Declaring a Popup control, the Quick and Dirty way.

The quickest and easiest way to create a pop up control is to declare the Popup in XAML.  I chose to use a Viewbox in this example to make sizing a little easier.  The following code can be added to any Panel or Canvas.

<Popup x:Name="PopupTest" AllowsTransparency="True">
    <Viewbox VerticalAlignment="Top">
        <TextBlock Text="Wow, that was easy!"/>
    </Viewbox>
</Popup>

Showing the Popup control.

Now create an event handler based on an action in your window.  I chose the MouseEnter event in this sample.The main parameters that need to be set here are Placement, StaysOpen and IsOpen.  Placement sets where the Popup will actually be placed, PlacementMode.Mouse is most likely what you want.  StaysOpen determines if the Popup will close if it loses focus.  Finally, IsOpen will make the Popup visible.

void Window_MouseEnter(object sender, MouseEventArgs e)
{
    PopupTest.Placement = System.Windows.Controls.Primitives.PlacementMode.Mouse;
    PopupTest.StaysOpen = false;
    PopupTest.Height = 1000;
    PopupTest.Width = 500;
    PopupTest.IsOpen = true;
}

Conclusion

Like I said, quick and dirty.  This method of Popups probably should be used any time you want a Popup that doesn’t need to be replicated throughout your application and doesn’t require dependency properties.  In future articles of this series I will demonstrate using some more complex Popup controls. 

I look forward to your comments and suggestions.  Please feel free to request future articles.

January 7, 2008 Posted by | C#, WPF, XAML | 8 Comments