Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing base class for WPF page code behind

Tags:

c#

wpf

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...

like image 754
uWat Avatar asked Jan 15 '23 01:01

uWat


2 Answers

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.

like image 198
yo chauhan Avatar answered Jan 31 '23 04:01

yo chauhan


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

like image 43
Rohit Vats Avatar answered Jan 31 '23 02:01

Rohit Vats