【问题标题】:Inheritance with Silverlight User Control Partial ClassesSilverlight 用户控件部分类的继承
【发布时间】:2011-08-25 04:12:18
【问题描述】:

我正在尝试允许多个类继承更通用的 Silverlight 用户控件,以避免我的代码中出现冗余。这些类继承扩展控件,然后继承用户控件类。我遇到的问题是每次编译时都会重新生成 ExtendedControlExtension.g.cs 文件,并且继承不正确(它继承了用户控件而不是我的扩展控件)。

请注意,我一直在继承 .cs 和 g.cs 文件中的扩展控件,但继续使用 .aspx 文件中的用户控件标记,因为这会导致错误

错误 29 XML 命名空间“http://schemas.microsoft.com/winfx/2006/xaml/presentation”中不存在标记“ExtendedControl”。

有没有办法解决这个问题?

谢谢!

【问题讨论】:

    标签: c# silverlight multiple-inheritance partial-classes user-controls


    【解决方案1】:

    您无法更改.g.cs 文件,事实上文件中已如此说明。此外,使用术语“自定义控件”是不幸的,因为这意味着特定的东西,而不是你想要做的事情。但是,好消息是您尝试做的事情是可能的。

    源自UserControl:

    public class FancyUserControl : UserControl
    {
        // Your added common functionality.
    }
    

    然后使用正常机制将新的UserControl 添加到您的项目中,比如说UserControl1。然后编辑UserControl.xaml文件如下:

    <local:FancyUserControl x:Class="SilverlightApplication1.UserControl1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SilverlightApplication1"
        mc:Ignorable="d"
        d:DesignHeight="300" d:DesignWidth="400">
    
        <Grid x:Name="LayoutRoot" Background="White">
    
        </Grid>
    </local:FancyUserControl>
    

    特别注意其中包含local 的三行,以适应您的应用程序。然后编辑UserControl1.xaml.cs文件如下:

    public partial class UserControl1 : FancyUserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }
    }
    

    Visual Studio 还不会很高兴,但最终重建您的项目,一切都会好起来的。

    UserControl1 类现在派生自 FancyUserControl 而不是 UserControl,您可以开始添加常用功能。要添加更多控件,您需要在最初将每个新控件添加到项目后手动编辑 XAML 和代码隐藏一次。

    【讨论】:

    • 感谢您提供非常完整的答案(我确实知道您不应该编辑 .gs 文件,但这是在您回答之前我能找到实现所需功能的唯一方法问题)!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多