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

Pan*_*nek 8 .net silverlight xaml code-behind resourcedictionary

我需要在资源字典后面添加代码,如本问题所述.(我知道这不是一个好习惯,但它应该基于链接问题的评论工作.)我用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>
Run Code Online (Sandbox Code Playgroud)

码:

using System.Windows;

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

        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

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

分析器内部错误:对象编写器 ' xClassNotDerivedFromElement '.System.Windows.Application.LoadComponent中的[Line:xxx Position:xxx].

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

小智 6

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


Pav*_*kov 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>
Run Code Online (Sandbox Code Playgroud)