tags:

views:

167

answers:

2

i would like to run some code onload of a form in wpf. is it possible to do this? im not able to find where to write code for form onload

judging by the responses below it seems like what i am asking is not something that is typically done? i mean in vb.net winforms its super easy you just go to the onload event, but for some reason in c# wpf is very difficult or there's no standard way to do this. can someone please tell me what is the best way to do this?

+3  A: 

You can subscribe to the Window's Loaded event and do your work in the event handler:

public MyWindow()
{
  Loaded += MyWindow_Loaded;
}

private void MyWindow_Loaded(object sender, RoutedEventArgs e)
{
  // do work here
}

Alternatively, depending on your scenario, you may be able to do your work in OnInitialized instead. See the Loaded event docs for a discussion of the difference between the two.

itowlson
Why do you subscribe to the event in the constructor instead of in the XAML?
Taylor Leese
Because this to me is logically part of the code -- the behaviour -- rather than the view (it's a workaround for the lack of a virtual OnLoaded method). For example, if I had to give the XAML to a graphic designer for editing in Blend, I'd prefer them not to be able to modify the Loaded event handling. It's a marginal call though!
itowlson
+1 - I totally agree with you...
Brent
+2  A: 

Use the Loaded event of the Window. You can configure this in the XAML like below:

<Window x:Class="WpfTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Your App" Loaded="Window_Loaded">

Here is what the Window_Loaded event would look like:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    // do stuff
}
Taylor Leese