Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understand WPF Window Events

Tags:

c#

events

wpf

I see Windows have a Loaded event, but not a Loading event (as there is Closing and Closed events).

My expectation was that the Loaded event would occur before the window is actually displayed. However, looking at the Window Lifetime Events, it shows that the Loaded event occurs after Activated event.

I put some initialization code in the Loaded event and there is a delay after the window is displayed and before my content appears. So what is the best event handler to use for window initialization that should occur before the window is displayed?

like image 600
Jonathan Wood Avatar asked Jun 22 '16 17:06

Jonathan Wood


People also ask

What are events in WPF?

WPF input events are generally implemented as a preview and bubbling pairs. Direct: Only event handlers on the event source are invoked. This non-routing strategy is analogous to Windows Forms UI framework events, which are standard CLR events.

What is bubbling and tunneling in WPF?

The difference between a bubbling and a tunneling event is that a tunneling event will always start with a preview. In a WPF application, events are often implemented as a tunneling/bubbling pair. So, you'll have a preview MouseDown and then a MouseDown event.

What is INotifyPropertyChanged in WPF?

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, that a property value has changed. For example, consider a Person object with a property called FirstName .


1 Answers

You can override OnStartup() in App.xaml.cs, and do stuff before calling base.OnStartup(e);. I just checked and this is fired before the window's constructor.

Alternatively, set the window's visibility to Hidden in its xaml file, do your initialization in the constructor and then set the visibility to Visible once done. This won't remove the delay, but the delay is only caused by whatever your initialization code is doing, so it's unavoidable unless you go asynchronous.

like image 134
Logix Avatar answered Oct 11 '22 16:10

Logix