【问题标题】:ArgumentException on setting DefaultStyleKey in custom control deriving from user control - Silverlight 4ArgumentException 在从用户控件派生的自定义控件中设置 DefaultStyleKey - Silverlight 4
【发布时间】:2011-09-18 11:56:42
【问题描述】:

我创建了用户控件MyUserControl。现在我想创建派生自 MyUserControl 的自定义控件 MyCustomControl。 MyCustomControl.cs 代码如下:

public class MyCustomControl : MyUserControl
    {
        public MyCustomControl()
        {
            this.DefaultStyleKey = typeof(MyCustomControl);
        }
    }

我有带有样式的 Themes/Generic.xaml 文件

<Style TargetType="local:MyCustomControl">
 ...
</Style>

在运行时实例化 MyCustomControl 我得到 ArgumentException 执行该行

this.DefaultStyleKey = typeof(MyCustomControl);

我错过了什么?

【问题讨论】:

    标签: silverlight silverlight-4.0


    【解决方案1】:

    通过抛出 ArgumentException 明确不允许将派生自 UserControl 的类型分配给 DefaultStyleKey(为什么 ArgumentException 以及为什么没有包含解释性消息,只有 SL 团队知道)。

    无法将UserControl 模板化,而是接收其自己的关联 Xaml。这就是UserControl 的全部意义所在。如果您希望以您尝试的方式继承它,您需要将 MyUserControl 转换为模板控件。

    【讨论】:

    • 我明白了。谢谢!是否可以使用其默认样式创建 CustomControl1,然后创建从 CustomControl1 派生的 CustomControl2,而 CustomControl2 也具有它自己的默认样式?最初我尝试了这种情况,但 System.Exception 在运行时发生
    猜你喜欢
    • 2012-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    相关资源
    最近更新 更多