Here I have showed a simple trick to define base class for WPF Window and UserControl.
While doing your program in WPF, you may have found problems creating a
BaseWindow Class to define methods that you often need may be for every page you define. Coming from ASP.NET programming, I have found this problem greatly as it could easily be done with ASP.NET Page class.
WPF throws a nasty error when we just modify the Base Class of a window in code behind to one which is created custom to us. Even I got the same few days back. Thank god I finally got it solved with some trick. In this article, I am going to share with you this little trick which might come very handy to you.
Basically the window Root element defines the Baseclass of the class you define. This is very essential. So if you have already changed baseclass of your window you must have to change the Root element of the XAML. Lets see the procedure with an example.
As I already told you, To make this happen I have defined one class, named as BaseWindow which
inherits from Window. In this class, it is important to define the
default constructor, as I am going to use this class as my Window.
Visual Studio implicitly calls the default constructor to create an
object to show the Designer. So the Class would look like :
public class BaseWindow : Window
public BaseWindow(string username)
this.UserName = username;
Now, lets create a new Window say of name Window1 (which comes as
default) and change the BaseClass from Window to BaseWindow. So the
code behind of the Window1 will look like :
public partial class Window1 : BaseWindow
Now, if you try to execute the project now, it would definitely throw
error to you. This is because, every WPF window is created from the
baseWindow layout rather than the current Window layout. In other
words, if you see the XAML, you will see the root tag is Window, which
is a class just parent of the current window. (In case of ASP.NET every
page inherits from its own code behind).
Thus to ensure everything works perfectly, we need to change the Root Element.
So it would look like :
title="Window1" height="300" width="300">
If you see this minutely, you can see I have added one namespace to my
project and named it as local. So BaseWindow should come from
BaseWindow and thus it goes like local:BaseWindow.
Now you can
see, the error goes out and you can work with your project as normally.
Please try out the sample application to have more clear idea on what I
want to tell you.
So you can see this could easily be achieved. Now you can define as many Baseclasses as you want, and associate with the Windows or UserControls. Make sure you define the Default constructor for each class you define to ensure that the window works perfectly.
Thanks for reading.