thecoop
thecoop

Reputation: 46138

How do I open a dialog as soon as an application is initialized?

I'm trying to open a modal dialog as soon as a WPF application has started (using ShowDialog(this)). I tried the following methods, both of which throw an InvalidOperationException, presumably because the window hasn't been initialized yet:

public MainWindow()
{
    InitializeComponent();

    ShowMyDialogDammit();
}

and:

public MainWindow()
{
    InitializeComponent();
}

protected override void OnInitialized(EventArgs e)
{
    base.OnInitialized(e);
    ShowMyDialogDammit();
}

How do I do this?

Upvotes: 2

Views: 60

Answers (3)

Scott Wisniewski
Scott Wisniewski

Reputation: 25061

Try this:

var w = new MainWindow();
w.ShowDialog();

You don't need the "ShowDialog" call inside the MainWindow class anywhere.

Upvotes: 0

Donut
Donut

Reputation: 112865

Add a handler for the FrameworkElement.Loaded event (which occurs "when the element is laid out, rendered, and ready for interaction"), and then open your dialog from within the event handler.
For example:

public MainWindow()
{
    InitializeComponent();

    // Adding the event handler
    Loaded += new RoutedEventHandler(IsLoaded);
}

private void Loaded(object sender, RoutedEventArgs e)
{
    ShowMyDialogDammit();
}

Upvotes: 3

Joel Lucsy
Joel Lucsy

Reputation: 8706

Try doing it from the Loaded event of your windows.

Upvotes: 1

Related Questions