tags:

views:

772

answers:

4

How do you display a custom UserControl as a dialog in C#/WPF (.NET 3.5)?

+15  A: 

Place it in a Window and call Window.ShowDialog.

private void Button1_Click(object sender, EventArgs e)
{
    Window window = new Window 
    {
        Title = "My User Control Dialog",
        Content = new MyUserControl()
    };

    window.ShowDialog(this);
}
sixlettervariables
+1 I didn't even think to do that dynamically, nice example! (better than mine :)
Pwninstein
Good example. This is what I was looking for.
Taylor Leese
The example could be shortened further, but that is left as an exercise for the reader ;-D
sixlettervariables
I also found that setting the SizeToContent = SizeToContent.WidthAndheight and ResizeMode = ResizeMode.NoResize were helpful so it lets the user control define the size.
Taylor Leese
A: 

As far as I know you can't do that. If you want to show it in a dialog, that's perfectly fine, just create a new Window that only contains your UserControl, and call ShowDialog() after you create an instance of that Window.

EDIT: The UserControl class doesn't contain a method ShowDialog, so what you're trying to do is in fact not possible.

This, however, is:

private void Button_Click(object sender, RoutedEventArgs e){
    new ContainerWindow().ShowDialog();
}
Pwninstein
A: 

I think mvermef ment the part about the Cinch implementation of Application.DoEvents.

Zenuka
A: 

If the answer by 'sixlettervariables' is modified as so, it works

private void button1_Click ( object sender, RoutedEventArgs e )                  
{
    Window window = new Window
    {
        Title = "My User Control Dialog",
        Content = new UserControl ( ),
        Height = 200,  // just added to have a smaller control (Window)
        Width = 240
    };

    window.ShowDialog ( );
}