A_A A_A - 2 years ago 85
C# Question

How to stop loading the Page from its constructor or an event before Loaded

I have a WPF Browser Application, it's got a StartupUri="StartPage.xaml"

and in the constructor for that Page I'm checking if it can

connect to a database which is on a server.

Now, if it fails, I'd like to stop loading that Page and navigate to a different one.

Trouble is - "A Page can only get a reference to its NavigationService when Page raises the Loaded event." (http://msdn.microsoft.com/en-us/library/ms750478.aspx)

...and by the time Loaded is raised, the page is already "starting to show",

which means if i navigate to another Page from Loaded event, it'll still show the first Page

(very briefly though) before loading the second Page.

So, how do i prevent this?

Since i know it shouldn't show up early when it's being constructed,

but the NavigationService at that time is null. This wouldn't be a problem if it weren't the first Page to load when my application starts. Maybe i can test the connection in the App: Application class (which is currently empty) and there decide what the StartupUri should be. If that's a good way, please provide a small example.
edit: Excavator

Answer Source

The approach you mentioned - putting the database check in the Application's OnStartup method - would work. But it would be horrible UX to block the UI, pre-startup, while you do a database lookup. Better to navigate first to a splash screen or something, as the startup page, and navigate from there as needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download