在 Silverlight 中使用 ResourceDictionary 时出错 [英] Error using ResourceDictionary in Silverlight
问题描述
在我的 Silverlight 应用程序中,我有 UserControl,我想引用位于单独 XAML 文件中的 ResourceDictionary 中的 StaticResource.
In my Silverlight app I have UserControl and I want to reference a StaticResource in a ResourceDictionary that is in a separate XAML file.
我的用户控件如下所示:
My UserControl looks like this:
<UserControl x:Class="ResourceDictionaryHeadache.MainPage"
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"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<UserControl.Resources>
<ResourceDictionary Source="/SampleData.xaml" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot">
<ListBox HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ItemsSource="{StaticResource SampleData}">
</ListBox>
</Grid>
</UserControl>
我的 SampleData.xaml 文件如下所示:
My SampleData.xaml file looks like this:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Headache="clr-namespace:ResourceDictionaryHeadache">
<Headache:PersonList x:Key="SampleData">
<Headache:Person Name="Joe" Age="20" />
<Headache:Person Name="Sam" Age="25" />
<Headache:Person Name="Dave" Age="30" />
</Headache:PersonList>
我将 SampleData.xaml 文件设置为 Content 的构建操作,当我运行应用程序时,我在 InitializeComponent() 行上收到 AG_E_PARSER_BAD_TYPE [Line: 5 Position: 44] 错误我的 UserControl 的构造函数.
I have the SampleData.xaml file set to a Build Action of Content and when I run the app I get an AG_E_PARSER_BAD_TYPE [Line: 5 Position: 44] error on the InitializeComponent() line of the constructor for my UserControl.
导致此错误的原因是什么,如何正确引用此资源?
What is causing this error and how can I correctly reference this resource?
推荐答案
资源字典中的这一行在我看来不正确:-
This line in your resource dictionary doesn't look right to me:-
xmlns:Headache="clr-namespace:ResourceDictionaryHeadache"
您的 PersonList
类是否真的定义在名为 ResourceDictionaryHeadache
的命名空间中?
Is your PersonList
class really defined in a Namespace called ResourceDictionaryHeadache
?
不管是不是我怀疑代码失败的原因是因为 XAML 找不到 PersonList
类型.
Whether it is or isn't I suspect that the reason the code it failing is because XAML can't find the PersonList
type.
编辑
天啊!我刚刚注意到,从 Source
中删除前面的/并将 SampleData.xaml 资源字典保留在其默认的页面"构建操作.
D'Oh! I just noticed, remove the preceding / from the Source
and leave the SampleData.xaml Resource dictionary at its default Build Action of "Page".
换句话说,如果您只是使用添加新项目"然后资源字典"添加了 XAML 文件,您将只需要在您的页面 xaml 中使用它:-
In other words if you just added the XAML file using "Add New Item" then "Resource Dictionary" you would only need this in your page xaml:-
<UserControl.Resources>
<ResourceDictionary Source="SampleData.xaml" />
</UserControl.Resources>
这篇关于在 Silverlight 中使用 ResourceDictionary 时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!