Purpose of InitializeComponent() in WPF and Why it is public in WPF in contrast to Winforms implementation

As it pertains to WPF applications, the method InitializeComponent() is quite a lot different than the one which was present in the earlier Winforms applications. InitializeComponent is actually a method defined on the interface System.Windows.Markup.IComponentConnector and is used for loading the compiled page of a component.

See MSDN excerpt below from this link which has more info:
IComponentConnector is used internally by Baml2006Reader.

Furthermore, InitializeComponent() method also exists in the compiled WPF application assembly and plays a role in the WPF application model of loading the XAML UI content at XAML parse time.

Implementations of InitializeComponent are widely observable as part of the infrastructure provided by frameworks or technologies that use XAML combined with application and programming models. For example, whenever you look at the generated classes for XAML root elements in WPF pages and applications, you will see InitializeComponent defined in the output.
InitializeComponent has to be in an interface and be public so that other outside WPF related assemblies in System.XAML namespace can make use of it and parse the XAML and generate the binaries.

InitializeComponent is also public (due to being part of an interface); to explain this further, go to the definition of InitializeComponent() method in your (say): Window1.g.cs class of say: WPFProject project, and change its access modifier from public to private

(keep the .g.cs file open in your project otherwise the build process re-generates this file, and you won't be able to see the error and access modifier will be reverted back to public again)

Now, when you compile your WPF project with private accessor to InitializeComponent being set, it throws a compile error as below:
Error 22 'WPFProject.Window1' does not implement interface member 'System.Windows.Markup.IComponentConnector.InitializeComponent()'. 'WPFProject.Window1.InitializeComponent()' cannot implement an interface member because it is not public.

Additionally, InitializeComponent() is marked with the [System.Diagnostics.DebuggerNonUserCodeAttribute()] attribute so you can't step into this method while debugging.

Happy WPFing.. ::VJSS::

Comments

Popular Posts