代码之家  ›  专栏  ›  技术社区  ›  Gergely Orosz

Visual Studio在不继承System.Windows.Controls.UserControl时覆盖UserControl父级

  •  1
  • Gergely Orosz  · 技术社区  · 15 年前

    我正在创建一系列具有类似业务逻辑的用户控件。因此,我尝试在所有这些用户控件都将继承的抽象基类中实现这个公共业务逻辑。继承链如下所示:

    system.windows.controls.usercontrol<--mycontrolBase(抽象)<--mycontrol1、mycontrol2等。

    我在Visual Studio中创建了myControl1、myControl2等类作为用户控件。我已经将类设置为从MyControlBase继承,而不是从System.Windows.Controls.UserControl继承。它很管用…直到对XAML进行更改并重新保存。然后,Visual Studio 2008重新分配要从System.Windows.Controls.UserControl继承的生成类。

    类和XAML的代码示例如下:

    // MyControlBase.cs:
    
        public abstract class MyControlBase.Windows.Controls.UserControl
        {
           public abstract void DoOperation1();
        }
    
    // MyControlBase.xaml: none
    
    // MyControl1.cs:
    
        public partial class MyControl1: MyControlBase
        {
            public MyControl1()
            {
                InitializeComponent();
            }
            public override void DoOperation1()
            {
               return;
            }
        }
    
    // MyControl1.xaml:
    
        <UserControl x:Class="Test.Controls.BarChart"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
            <Grid x:Name="LayoutRoot" Background="Blue">
    
            </Grid>
        </UserControl>
    
    // mycontrol1.g.cs (generated by Visual Studio) orginally
    
        public partial class MyControl1: System.Windows.Controls.UserControl
        {
    
            internal System.Windows.Controls.Grid LayoutRoot;
    
            // InitilizeComponent() etc
    
        }
    
    // mycontrol1.g.cs (generated by Visual Studio) modified by me
    
    public partial class MyControl1: MyControlBase
        {
    
            internal System.Windows.Controls.Grid LayoutRoot;
    
            // InitilizeComponent() etc
        }
    

    每当在Visual Studio 2008编辑器中编辑mycontrol1.xaml时,在保存它之后,修改后的mycontrol1.g.cs都会将自身还原为原始的mycontrol1.g.cs(同时:再次从system.windows.controls.usercontrol继承)。然后编译失败,因为MyControl1的两个部分类不是从同一父类继承的:vs生成的一个继承自System.Windows.Controls.UserControl,我的代码是从MyControlBase继承的。

    有办法解决这个问题吗?我想拥有从抽象类继承的能力,并假设有一种方法让Visual Studio允许我,我只是不知道我缺少什么。或者,UserControl的概念继承自System.Windows.Controls.UserControl之外的其他类,这是一个错误的概念吗?

    1 回复  |  直到 12 年前
        1
  •  1
  •   Bryant    15 年前

    您需要将XAML更改为从MyControlBase继承而不是从UserControl继承:

    <my:MyControlBase
      xmlns:my="MyNamespace"
      x:Class="Visiblox.Charts.Test.Controls.BarChart"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
       <Grid x:Name="LayoutRoot" Background="Blue">
       </Grid>
    </my:MyControlBase>
    

    这就是为什么在编辑XAML时,Visual Studio会不断更改基类。