adam.k
adam.k

Reputation: 404

is it good practice to call .Show() or .ShowDialog inside dialog's constructor

Is it a good practice to call .Show() or .ShowDialog() method as the last line of WPF window constructor? The only reason is to simplify using my window class - by creating an instance of it I'm already displaying it.

Upvotes: 2

Views: 757

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460238

I'd say bad practice. What if you wanted to create instances without showing them?

Instead you could provide a factory method that does this:

public static void ShowMyDialog(string text)
{
    // initialize an instance of this dialog 
    // ... and then show
    instance.ShowDialog();
}

Upvotes: 6

ASh
ASh

Reputation: 35720

there is a scenario with inheritance where your suggested approach breaks spectacularly:

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        Title = "W 1";
        ShowDialog();
    }
}

public partial class Window2 : Window1
{
    public Window2()
    {
        InitializeComponent();
        Title = "W 2";
    }
}

an attempt to create var w = new Window2(); will block execution of Window2 ctor until modal window with "W 1" title is closed. w.ShowDialog() will throw an exception after that.

under normal coditions user may want to set some properties of Window before showing it, e.g. to set DataContext.

so don't break single-responsibility principle and let constructor and ShowDialog method do their job separately

Upvotes: 0

Related Questions