Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Role of Parameterless constructor in WPF (XAML)

Tags:

wpf

xaml

I've been reading an online tutorial on WPF, there I read a line "All classes in WPF have parameterless constructors and make excessive usage of properties. That is done to make it perfectly fit for XML languages like XAML."

I examined above words by creating a custom class with one parameterized constructor and encountered error "Type 'custom_class_name' is not usable as an object element because it is not public or does not define a public parameterless constructor or a type converter."

I just wanted to know a specific detailed reason, how parameterless constructors help achieving this.

like image 454
Gautam G Avatar asked Sep 17 '13 11:09

Gautam G


1 Answers

The WPF Framework uses the parameter-less constructors to instantiate all of the objects that we define in our XAML pages when it builds the visual tree. If it tries to instantiate an object that does not have a public parameter-less constructor, then you will throw this Exception. If you were to add a parameter-less constructor to your object and try again, then this Exception should disappear.

Please also look at the Type '{0}' is not usable as an object element page at MSDN.

Also, I believe that classes without any constructors in .NET are automatically provided with 'invisible' parameter-less constructors by default. However, if we add a parameterised constructor, then no parameter-less constructor will be provided automatically.

like image 122
Sheridan Avatar answered Oct 02 '22 08:10

Sheridan