在Silverlight中向Resource Dictionary添加Code Behind时出现xClassNotDerivedFromElement错误

时间:2010-07-30 10:37:37

标签: .net silverlight xaml code-behind resourcedictionary

我需要按照this question中的描述将类后面的代码添加到资源字典中。 (我知道这不是一个好习惯,但它应该基于链接问题的注释工作。)我用x:Class属性引用代码:

XAML(单独的资源字典文件):

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="MyNamespace.MyStandardResources">
    ...
</ResourceDictionary>

CODE:

using System.Windows;

namespace MyNamespace
{
    public partial class MyStandardResources : ResourceDictionary
    {
        public MyStandardResources()
        {
            InitializeComponent();
        }

        //...
    }
}

这会导致运行时解析器异常:

Parser内部错误:对象编写者' xClassNotDerivedFromElement '。 System.Windows.Application.LoadComponent上的[Line:xxx Position:xxx]。

资源包含在带有ResourceDictionary.MergedDictionaries标记的App.xaml中。

3 个答案:

答案 0 :(得分:6)

您是否尝试将此ResourceDictionary用作合并字典的Source值?如果是这样,则不支持。你得到xClassNotDerivedFromElement错误,这是一种奇怪的方式来表示它,但这就是原因:Source属性值以一种将XAML引用为XAML而不是作为类的方式进行转换。 XAML解析器将XAML作为纯加载操作打开,没有任何预编译的好处,并且当时无法协调x:Class。

答案 1 :(得分:5)

对于App.xaml中的合并字典,x:Class受到限制。相反,您应该使用在App资源中定义为代码的类:

<Application xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
         x:Class="MyNamespace.App"
         xmlns:view="clr-namespace:MyNamespace">

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <view:MyStandardResources />
                ....
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

</Application>

答案 2 :(得分:0)

遗憾的是,为资源字典创建代码隐藏现在意味着您无法使用xaml的URI创建ResourceDictionary。

我再次删除了我的代码隐藏,但仍使用此question+and+answer的答案在代码中创建了ResourceDictionary

基本上它只是创建一个空的ResourceDictionary并将其Source设置为代码中的xaml uri。

对我而言,这样做效果更好,因为这意味着如果他们愿意,其他任何人仍然可以引用资源字典,并以“预期”方式进行。