uWat
uWat

Reputation: 147

Changing base class for WPF page code behind

I have a simple class called CustomPage which inherits from Window:

public class CustomPage : Window 
{
    public string PageProperty { get; set; }
}

I want my MainWindow codebehind to inherit from CustomPage as follows:

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

Unfortunately, I get the following error:

Partial declarations of 'WpfApplication1.MainWindow' must not specify different base classes

I can set x:Class to "WpfApplication1.CustomPage" in MainWindow.xaml, but then it appears I don't have access to the UI elements defined in MainWindow.xaml...

Upvotes: 6

Views: 4587

Answers (2)

yo chauhan
yo chauhan

Reputation: 12295

public partial class MainWindow 
{
    public MainWindow()
    {
        InitializeComponent();

    }
}

public class CustomPage : Window
{
    public string PageProperty { get; set; }
}

<myWindow:CustomPage x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:myWindow="clr-namespace:WpfApplication4"
    Title="MainWindow" Height="800" Width="800">
<Grid>
</Grid>
</myWindow:CustomPage>

I hope this will help.

Upvotes: 7

Rohit Vats
Rohit Vats

Reputation: 81243

You need to update your xaml like this -

<local:CustomPage x:Class="WpfApplication4.MainWindow"
                  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
                  xmlns:local="clr-namespace:WpfApplication1">
</local:CustomPage>

Here, local is your namespace where CustomPage and MainWindow resides.

As the error suggested, you can't declare different base classes for partial declaration of class. So, in XAML too, you need to use the CustomPage instead of WPF Window

Upvotes: 4

Related Questions