In WinForm's control, there is an OnLoaded virtual function, but this seems to be missing in WPF control. I found this function very useful in some situations. For example, I could do something here after the control is "completely" initialized. In WPF control, there is an OnInitialized virtual function, but this function is called from InitializeComponent function which is too early and it doesn't allow derived class to setup. Is there any reason not to have this function in WPF? Or did I miss anything?
Asked
Active
Viewed 1.0k times
2 Answers
9
You can attach to the Loaded event of your Window object and do what you want to do inside the event handler (assuming you are using c#):
public MyWindow() //constructor
{
this.Loaded += MyWindow_Loaded;
}
private void MyWindow_Loaded(object sender, RoutedEventArgs e)
{
// do your stuff here
}

Edwin de Koning
- 14,209
- 7
- 56
- 74
-
2I know I could work it around like this, but I'm more curious why WPF removed that function. In fact, I was also wondering why OnLoaded was removed as a virtual function in WPF Window. Now, I have to do this extra hook to get back my Loaded function. Why? – newman Jul 04 '11 at 07:30
-
@miliu: I think the main reason is that in WinForms, OnLoad was a very important part of the (event-based) system. Certain things could only be done at that point in the Application lifecycle. In WPF however there is no real need to expose this event handler to the user. The framework does not use it (hence it's not virtual), so why should you? – Edwin de Koning Jul 04 '11 at 07:57
-
Thanks. This sounds reasonable. – newman Jul 04 '11 at 14:17
0
you will be looking for FrameworkElement.EndInit()
This will work after the initialization process of the Element...

Binil
- 6,445
- 3
- 30
- 40
-
1I don't understand how the EndInit() function can help me here. Can you please elaborate? – newman Jul 04 '11 at 07:32
-
1as you mentioned in your question `"I could do something here after the control is "completely" initialized"` – Binil Jul 04 '11 at 07:36
-
6EndInit isn't called after the control is completely initialized. It's called before OnApplyTemplate. – Glenn Maynard Feb 09 '17 at 23:57