WPF - UserControl继承

时间:2010-10-20 20:51:00

标签: wpf inheritance user-controls wpf-controls

我在WPF中遇到控件继承问题。我创建了一个名为BaseUserControl的UserControl。我希望此控件成为其他WPF userControl的基本控件。所以我写了另一个名为FirstComponent的UserControl。在下一步中,我更改了此代码

FirstComponent : UserControl

到这个

FirstComponent : BaseControl

但是在编译期间我收到此错误

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

如何使FirstComponent从BaseControl派生?

EDIT 感谢abhishek的回答,我设法继承了控件。我有另一个问题。在基类中我指定了一个属性public Grid _MainGrid {get;组; }。现在我想在我的派生类中创建一个这个网格的实例。所以我使用了这段代码           Howerver我收到错误属性'_MainGrid'没有值。 8号线位置36.

3 个答案:

答案 0 :(得分:5)

你看到我的完整文章了吗?

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

我希望这会对你有所帮助。

  

如果您尝试执行该项目,肯定会抛出错误   您。这是因为,每个WPF窗口都是从baseWindow创建的   布局而不是当前的窗口布局。换句话说,如果你   看到XAML,你会看到根标签是Window,它是一个类   只是当前窗口的父级。

     

因此,为了确保一切正常,我们需要更改Root   元件。

     

所以它看起来像:

<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

答案 1 :(得分:0)

初始错误的原因是因为该类实际上是一个部分类,除了您更改基类的位置之外,还在其他地方列出了特定的基本继承。

至于你的财产'继承',我建议尝试

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

   set 
   { 
      base.MainGrid = value; 
   } 
}

但是我应该注意,这不会为您提供指向基类的任何现有实例的链接。如果您希望派生类中的保证链接到该Grid的单个实例,则必须使基类属性为静态。 在这种情况下,您的代码将如下所示......

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

    set
    {
        BaseControl.MainGrid = value;
    }
}

答案 2 :(得分:0)

在XAML.cs文件中为Usercontrol指定Different基类

 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>