4

我有一个Silverlight类库,名为MyClassLibrary。试图使用ResourceDictionary,但它的样式没有找到

其中,我有一个用户控件,称为MyControl。

在控制我定义用户资源:

<UserControl.Resources> 
    <Style x:Key="ComboBoxStyle" TargetType="ComboBox"> 
     (lots of xaml) 
    </Style> 
</UserControl.Resources> 

控制消耗的风格是这样的:

<ComboBox Style="{ StaticResource ComboBoxStyle }"></ComboBox> 

这一切能够完美的组合框附带了正确的风格,所以我知道风格写得正确。

我真正想要的是将样式放在资源字典中,以便可以在此程序集中使用几种不同的控件。所以我在SAME程序集中创建了一个资源字典。我称之为ResourceDictionary.xaml。

我将Style定义从我的用户控件移动到资源字典。

所以后来资源字典是这样的:

<ResourceDictionary 
xmlns="etc" > 
    <Style x:Key="ComboBoxStyle" TargetType="ComboBox"> 
     (lots of xaml) 
    </Style> 
</ResourceDictionary> 

控制的用户资源,现在看起来是这样的:

<UserControl.Resources> 
    <ResourceDictionary 
    Source="/MyClassLibrary;component/ResourceDictionary.xaml" x:Name="resDict"/> 
</UserControl.Resources> 

而控制作为前仍消耗的风格完全相同的方式。

现在我知道它正在查找ResourceDictionary.xaml文件,因为我试图将“Source”属性更改为NonExistentFile.xaml,并且它抱怨说它无法找到该文件。它没有对ResourceDictionary.xaml提出这种抱怨,所以我认为它找到了它。

但是,当我运行该应用程序时,出现“无法使用名称/键ComboBoxStyle查找资源”的错误。

我在做什么错?这看起来很简单,并且不起作用。

在此先感谢您提供的任何帮助。

+0

Repro:创建一个SilverlightClassLibrary,添加一个“Silverlight用户控件”,添加一个“Silverlight资源字典”。将一个样式(称为MyStyle)添加到资源字典(对于ContentControl前景红色),将一个ContentControl添加到用户控件中,指向{StaticResource MyStyle}中的Style。最后,使用Source路径将ResourceDictionary添加到usercontrol资源中,就像您拥有它一样。将Silverlight应用程序添加到解决方案中,引用类库项目,将库控件的实例添加到MainPage的Xaml。运行,工作正常,如预期的那样具有红色前景。 – AnthonyWJones 2010-01-30 18:35:21

+0

换句话说,我看不出你在做什么有什么问题。你能提供任何其他细节,可能会使你所做的与Repro不同吗? – AnthonyWJones 2010-01-30 18:37:10

回答

2

不知道这是否有助于准确,但我有我的ResourceDictionaries中的App.xaml:

<Application.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="Sausage/Bangers.xaml"/> 
      <ResourceDictionary> 
       .. other stuff, e.g. 
       <helpers:NotOperatorValueConverter x:Key="NotOperatorValueConverter" /> 
      </ResourceDictionary> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Application.Resources> 

即使你不喜欢的方式,你可以看到我的资料来源=跟你不一样。

+0

我同意使用MergedDictionaries是一种更好的模式,因为它允许UserControl除了包含外部资源之外还拥有其他自己的资源。不过,我认为你已经错过了Dia正在建立一个控制库的事实。没有App.Xaml。此外,输出是一个dll而不是xap,因此您拥有的源路径不能用于添加到库项目的资源字典。组件资源路径是必需的。 – AnthonyWJones 2010-01-30 18:22:35

+0

你说得对:到最后的时候,我已经忘记了这一点。 – serialhobbyist 2010-01-30 18:46:35

0

谢谢你们两位,你们的回答确实让我解决了它。

我真的有什么事情是这样的:

<UserControl.Resources> 
    <Style ...> stuff </Style> 
</UserControl.Resources> 

要我加入我的所以它看起来像这样

<UserControl.Resources> 
    <Style ...> stuff </Style> 
    <ResourceDictionary Source="..." /> 
</UserControl.Resources> 

现在,这个编译非常beatifully只是将无法运行。我不明白我需要使用MergedDictionaries。于是我得到了这个概念并重新组织了这个部分,现在这一切都很精美。

非常感谢!

相关问题