2010-10-20 103 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>