【问题标题】:Trying to use a ResourceDictionary, but styles in it come up as not found尝试使用 ResourceDictionary,但其中的样式显示为未找到
【发布时间】:2010-01-29 23:22:34
【问题描述】:

我有一个名为 MyClassLibrary 的 Silverlight 类库。

在其中,我有一个名为 MyControl 的用户控件。

在控件中我定义了用户资源:

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

控件使用如下样式:

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

这一切都很完美,ComboBox 提供了正确的样式,所以我知道样式写对了。

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

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

那么资源字典看起来像这样:

<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 的资源”的错误。

我做错了什么?这看起来很简单,但它不起作用。

提前感谢您能给我的任何帮助。

【问题讨论】:

  • Repro:创建了 SilverlightClassLibrary,添加了“Silverlight 用户控件”,添加了“Silverlight 资源字典”。将 Style(称为 MyStyle)添加到 Resource 字典(对于 ContentControl 前景红色),将 ContentControl 添加到用户控件,将 Style 指向 {StaticResource MyStyle}。最后,使用源路径将 ResourceDictionary 添加到用户控件资源中,就像您拥有它一样。将 Silverlight 应用程序添加到解决方案,引用类库项目,将库控件的实例添加到 MainPage 的 Xaml。运行,工作正常,有预期的红色前景。
  • 换句话说,我看不出你所做的有什么问题。您能否提供任何其他可能使您所做的事情与我的 Repro 不同的细节?

标签: silverlight resources coding-style resourcedictionary staticresource


【解决方案1】:

不确定这是否有帮助,但我将我的 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>

即使您不喜欢这种方法,您也可以看到我的 Source= 与您的不同。

【讨论】:

  • 我同意 MergedDictionaries 的使用是一种更好的模式,因为它允许 UserControl 除了包含外部资源之外还拥有自己的其他资源。但是我认为您已经错过了 Dia 正在构建控制库的事实。没有 App.Xaml。此外,输出是 dll 而不是 xap,因此您拥有的源路径类型不能与添加到库项目的资源字典一起使用。需要一个组件资源路径。
  • 你说得对:当我走到最后时,我已经忘记了。
【解决方案2】:

谢谢你们两个,你们的回答确实让我解决了这个问题。

我真正拥有的是这样的:

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

然后我添加了我的,所以它看起来像这样

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

现在这个编译得非常漂亮,但就是无法运行。我不明白我需要使用 MergedDictionaries。所以我得到了这个概念并重新组织了这个部分,现在一切都很好。

非常感谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2019-09-15
    • 1970-01-01
    相关资源
    最近更新 更多