2010-10-20 102 views
5

我在WPF控件繼承有問題。我創建了一個名爲BaseUserControl的UserControl。我想讓這個控件成爲其他WPF用戶控件的基本控件。所以我寫了另一個叫做FirstComponent的UserControl。在下一步我不過在編譯過程中改變了這種代碼wpf - 用戶控件繼承

FirstComponent : UserControl 

這個

FirstComponent : BaseControl 

我得到這個錯誤

Partial declarations of 'controlinheritance.componenets.FirstComponent' must not specify different base classes 

我應該怎麼做,使FirstComponent從BASECONTROL派生?

編輯 感謝abhishek答案我設法繼承控件。我有另一個問題。在基類中,我指定了一個屬性public Grid _MainGrid {get;組; }。現在我想在我的派生類中創建這個網格的一個實例。所以我用這個代碼 Howerver我得到一個錯誤屬性'_MainGrid'沒有值。 Line 8 Position 36.

回答

5

您是否看到過我的完整文章?

http://www.dotnetfunda.com/articles/article832-define-base-class-for-window--usercontrol-.aspx

我希望這將幫助你在這。

如果您嘗試執行該項目,它肯定會向您發送錯誤 。這是因爲,每個WPF窗口都是從baseWindow 佈局而不是當前的窗口布局創建的。換句話說,如果你看到XAML,你會看到根標籤是Window,它是當前窗口的父類 。

因此,爲了確保一切正常,我們需要更改根元素 元素。

因此,它看起來像:

<local:BaseWindow Class="BaseWindowSample.Window1" 
        Name="winImp" 
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:local="clr-namespace:BaseWindowSample" 
        Title="Window1"> 
... 
</local:BaseWindow> 

如果你看到這個微小的,你可以看到我已經添加了一個命名空間來我 項目,並把它命名爲本地。所以BaseWindow應該來自 BaseWindow,因此它會像地方:BaseWindow

+0

感謝它幫了我很多。你能看看我的edigted消息 – Berial 2010-10-20 21:08:32

0

那麼初始誤差的原因是因爲該類實際上這是除了列出一個特定的基本繼承其他地方的分部類你改變你的基類的位置。

至於你的財產「繼承」,我建議嘗試

public Grid MainGrid 
{ 
    get 
    { 
     return base.MainGrid; 
    } 

    set 
    { 
     base.MainGrid = value; 
    } 
} 

但是我要指出,這不會給你一個鏈接到你的基類的任何現有實例(一個或多個)。如果你希望在你的派生類中有一個有保證的鏈接到那個Grid的唯一實例,那麼你將不得不使基類屬性成爲靜態的。 在這種情況下,您的代碼將如下所示...

public Grid MainGrid 
{ 
    get 
    { 
     return BaseControl.MainGrid; 
    } 

    set 
    { 
     BaseControl.MainGrid = value; 
    } 
} 
0

當你指定一個不同的基類的用戶控件在XAML.cs文件

FirstComponent : BaseControl 

你也應該在XAML改變這種

<Base:BaseControl x:Class="FirstComponent" 
      xmlns:Base="clr-namespace:MyApplication.Base" 
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      mc:Ignorable="d" 
      d:DesignHeight="300" d:DesignWidth="300"> 
    <Grid> 


    </Grid> 
</Base:BaseControl>