【问题标题】:Deriving from UserControl in Silverlight从 Silverlight 中的 UserControl 派生
【发布时间】:2009-03-16 16:07:06
【问题描述】:

在 Silverlight 2 中,我有以下控件类声明:

public partial class ClassX : UserControl

我希望用派生自 UserControl 的 ClassXBase 替换 UserControl,但我得到了合理的错误“'ClassX' 的部分声明不能指定不同的基类”

但是,我找不到另一个部分类来替换它的基类。知道这个其他部分类在哪里或我是如何做到的吗?

【问题讨论】:

    标签: silverlight silverlight-2.0


    【解决方案1】:

    如果包含 UserControl 基类的命名空间,则只要使用命名空间即可。例如:

    public abstract class MyBaseUserControl : UserControl
    {
      // ...
    } 
    

    那么你必须在 XAML 中使用这个类(注意我的命名空间,然后使用新的命名空间作为文档的根):

    <!-- Page.xaml -->
    <my:BaseUserControl 
        x:Class="SilverlightApplication11.Page"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:my="clr-namespace:SilverlightApplication11"
        Width="400" Height="300">
        <Grid x:Name="LayoutRoot" Background="White">
    
        </Grid>
    </my:BaseUserControl>
    

    这不会神奇地更改代码隐藏中的基类,因此将该代码更改为您的基类:

    public partial class Page : BaseUserControl
    {
      public Page()
      {
        InitializeComponent();
      }
    }
    

    【讨论】:

    • 或者更好的是,从您的代码隐藏中完全删除基类声明。
    【解决方案2】:

    UserControl 的分部类由 XAML 定义,框架希望它派生自 UserControl。你想达到什么目的?使用封装而不是继承可能会更好。如果您必须使用继承,那么从其他类派生您可能会更好地从其他控件类(如 ContentControl 或 Control)派生。 Jesse Liberty 在Silverlight.net 上做了一个great series of videos

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      相关资源
      最近更新 更多