I would like to run some code onload of a form in WPF. Is it possible to do this? I am 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 in WPF? In Vb.Net winforms it is easy, you just go to the onload event and add the code that you need ran on load. For whatever reason, in C# WPF it seem very difficult or there is no standard way to do this. Can someone please tell me what is the best way to do this?
Remarks. Raising an event invokes the event handler through a delegate. For more information, see Handling and Raising Events. The OnLoad method also allows derived classes to handle the event without attaching a delegate.
Load += new EventHandler(ProgramViwer_Load); A third way using the designer (probably the quickest) - when you create a new form, double click on the middle of it on it in design mode. It'll create a Form load event for you, hook it in, and take you to the event handler code.
The Form Load Event in VB . NET. An important event you'll want to write code for is the Form Load event. You might want to, for example, set the Enabled property of a control to False when a form loads. Or maybe blank out an item on your menu.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With