2012-11-14 23 views
2

我有一個叫CustomPage簡單的類,它從窗口繼承WPF頁面代碼:更改基類的背後

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

我想我的主窗口的代碼隱藏從CustomPage繼承如下:

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

不幸,我得到以下錯誤:

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

我可以將x:Class設置爲「WpfApplication 1.CustomPage」在MainWindow.xaml,但隨後便出現我沒有獲得在MainWindow.xaml定義的UI元素...

+0

您應該看到這篇文章:[在WPF中創建基本窗口類](http://weblogs.asp.net/psheriff/archive/2009/11/02/creating-a-base-window-class-in -wpf.aspx) – Habib

回答

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

我希望這將有助於。

+0

除非在後面的代碼中繼承'CustomPage'中的'MainWindow',否則這將不起作用。 –

+0

xaml最終轉換爲部分類與它的代碼相同的名稱,這就是爲什麼後面的代碼總是部分的,所以它沒關係 – ethicallogics

+0

噢。我不知何故錯過了它。爲它+1。 :) –

2

你需要更新你的XAML這樣的 -

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

這裏,local是您的名字空間,其中CustomPageMainWindow駐留。

由於錯誤提示,您不能聲明不同的基類以部分聲明類。所以,在XAML也一樣,你需要使用CustomPage而不是WPF Window