Elephantik
Elephantik

Reputation: 2008

Create an instance of a window which is not directly derived from WPF Window

I have the following hierarchy of classes:

abstract MyWindowBase : System.Windows.Window (i.e. the WPF one)

MyWindow : MyWindowBase

I want to create a Window of type MyWindow as a root element in XAML. I found only this way of doing it:

<local:MyWindowBase
    x:Class="MyWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    local:x="clr-namespace:MyProjectNamespace">

    <local:MyWindowBase.Resources>...</local:MyWindowBase.Resources>

    ...

</local:MyWindowBase>

I.e. I'm specifing my abstract type as the root element, which seems awkward.

I also tried the obvious way:

<Window
    x:Class="MyWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    ...
</Window>

and defining MyWindow : MyWindowBase in code-behind, but it clashes with the class definition in the generated file which says MyWindow : Window.

Is there a better way? Thanks

Upvotes: 0

Views: 334

Answers (3)

Vicro
Vicro

Reputation: 575

It is the normal usage. You are actually doing the same using the default classes created by Visual Studio or Blend.

Notice that you are inheriting from Window, so the actual class is MainWindow, but the xaml uses the base class Window

C#

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

Xaml

<Window
  x:Class="MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  ...
</Window>

Upvotes: 0

slugster
slugster

Reputation: 49965

Check this recent post of mine which explains exactly this sort of thing - how to derive one page from another (the methodology is exactly the same).

Upvotes: 1

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59151

There is nothing preventing you from having whatever hierarchy you want here. The root element is the base type, and x:Class is the generated type you are currently defining.

If you want the specific class to be called MyWindow and derived from MyWindowBase, your first example is correct:

<local:MyWindowBase
    x:Class="MyWindow"
    local:x="clr-namespace:MyProjectNamespace">

If you want the specific class to be derived from MyWindow, then you need a different class name for it:

<local:MyWindow
    x:Class="MainWindow"
    local:x="clr-namespace:MyProjectNamespace">

Upvotes: 0

Related Questions