Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does InitializeComponent() do, and how does it work in WPF?

People also ask

What is the use of InitializeComponent in C#?

The InitializeComponent method contains the code that creates and initializes the user interface objects dragged on the form surface with the values provided by you (the programmer) using the Property Grid of the Form Designer.

What does InitializeComponent do xamarin?

InitializeComponent() method in Visual Studio.NET C# or VB.NET is method that is automatically created and managed by Windows Forms designer and it defines everything you see on the form. Everything done on the form in VS.NET using designers generates code.

What is the meaning of WPF?

WPF stands for Windows Presentation Foundation. It is a powerful framework for building Windows applications.


The call to InitializeComponent() (which is usually called in the default constructor of at least Window and UserControl) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).

This method locates a URI to the XAML for the Window/UserControl that is loading, and passes it to the System.Windows.Application.LoadComponent() static method. LoadComponent() loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.

In more detail, LoadComponent creates an instance of the XamlParser, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode(). This gets passed to the BamlRecordWriter class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.

Note: Interestingly, the InitializeComponent is a method on the System.Windows.Markup.IComponentConnector interface, of which Window/UserControl implement in the partial generated class.

Hope this helps!


Looking at the code always helps too. That is, you can actually take a look at the generated partial class (that calls LoadComponent) by doing the following:

  1. Go to the Solution Explorer pane in the Visual Studio solution that you are interested in.
  2. There is a button in the tool bar of the Solution Explorer titled 'Show All Files'. Toggle that button.
  3. Now, expand the obj folder and then the Debug or Release folder (or whatever configuration you are building) and you will see a file titled YourClass.g.cs.

The YourClass.g.cs ... is the code for generated partial class. Again, if you open that up you can see the InitializeComponent method and how it calls LoadComponent ... and much more.