Error using ResourceDictionary in Silverlight

◇◆丶佛笑我妖孽 提交于 2019-12-23 20:14:16

问题


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>

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?


回答1:


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>



回答2:


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.



来源:https://stackoverflow.com/questions/2025152/error-using-resourcedictionary-in-silverlight

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!