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>
&l开发者_开发问答t;Grid x:Name="LayoutRoot">
<ListBox HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
ItemsSource="{StaticResource SampleData}">
</ListBox>
</Grid>
</UserControl>
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>
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?
Set the Build Action to Resource and then reference it like below:
<ResourceDictionary Source="/AssemblyName;component/sampledata.xaml" />
make sure that its all in lowercase from component onwards as thats how it ends up in the resources of the dll.
This line in your resource dictionary doesn't look right to me:-
xmlns:Headache="clr-namespace:ResourceDictionaryHeadache"
Is your PersonList
class really defined in a Namespace called ResourceDictionaryHeadache
?
Whether it is or isn't I suspect that the reason the code it failing is because XAML can't find the PersonList
type.
Edit
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".
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>
精彩评论