WPF - UserControl 继承

5

我在WPF中遇到了控件继承的问题。我创建了一个名为BaseUserControl的UserControl。我希望这个控件成为其他WPF用户控件的基础控件。因此,我又编写了另一个名为FirstComponent的UserControl。在下一步中,我更改了以下代码:

FirstComponent : UserControl

转换为:

FirstComponent : BaseControl

然而,在编译过程中我遇到了这个错误。

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

我应该怎么做才能让FirstComponent从BaseControl派生出来?

编辑 感谢abhishek的回答,我成功地继承了控件。然而我有另一个问题。在基类中,我指定了一个公共属性_Grid_MainGrid{get;set;}。现在我想在我的派生类中创建这个网格的实例。所以我使用了这段代码

然而,我得到一个错误“属性'_MainGrid'没有值。第8行第36位置。”

3个回答

5

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

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

希望这能对你有所帮助。

If you try to execute the project, it would definitely throw error to you. This is because, every WPF window is created from the baseWindow layout rather than the current Window layout. In other words, if you see the XAML, you will see the root tag is Window, which is a class just parent of the current window.

Thus to ensure everything works perfectly, we need to change the Root Element.

So it would look like :

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

If you see this minutely, you can see I have added one namespace to my project and named it as local. So BaseWindow should come from BaseWindow and thus it goes like local:BaseWindow


谢谢,它对我帮助很大。能否请您看一下我编辑过的信息? - Berial

0

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

至于您的属性“inheritance”,我建议尝试

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

   set 
   { 
      base.MainGrid = value; 
   } 
}

然而,我应该指出这不会给您提供到基类任何现有实例的链接。如果您希望在派生类中有一个保证的链接到该网格的唯一实例,则必须将基类属性设置为静态。 在这种情况下,您的代码将如下所示...

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

    set
    {
        BaseControl.MainGrid = value;
    }
}

0
当您在XAML.cs文件中为Usercontrol指定一个不同的基类时
 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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接