Skip to content

How to create class partially in XAML and partially in code?

May 2, 2009

C# supplies us with a nice feature allowing to create such splitted class definition. It’s called partial class. Partial classes were added to allow for an easy integration with generated code. For example managed C++ does not support it (some say it is a good thing) which makes it much harder to use WPF with this language.

In our case it would look like this.

  1: <Window
  2:     xmlns="http://schemas.microsoft.com/netfx/2007/xaml/presentation"
  3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4:     x:Class="DatabaseGui.MainWindow"
  5:     >
  6:
  7: </Window>
  8: 
  1: namespace Database
  2: {
  3:     public partial class MainWindow : Window
  4:     {
  5:         public MainWindow()
  6:         {
  7:             InitializeComponent();
  8:         }
  9:     }
 10: }

From code’s perspective what is important is this partial keyword telling compiler that it is only a partial definition of MainWindow class. Compiler will look for all parts of that class and join them together.

For XAML’s perspective we can omit x:Class attribute. It has more less the same meaning as partial keyword used in code.
If we use x:Class in our XAML than, during XAML compilation new file MainWindow.g.cs is created. It contains automatically generated partial class for our MainWindow that does a lot of useful magic behind the scene. It contains a private field for any named element defined in XAML (that’s why you can use such elements so easy in your code-behind). It also contains InitializeComponent method that loads BAML resource, assigns fields to appropriate instances originally declared in XAML, and hook up events if any were specified in XAML. That is why it is so important to call InitializeComponent in MainWindow’s constructor.

Advertisement

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.