【问题标题】:How to override ResourceDictionary values如何覆盖 ResourceDictionary 值
【发布时间】:2014-08-22 15:54:46
【问题描述】:

我有一个这样的资源字典:

<ResourceDictionary>
    <SolidColorBrush x:Key="SpecialColor" Color="Yellow" />
    <DataTemplate x:Key="SpecialTemplate">
        <Rectangle Fill="{StaticResource SpecialColor}" />
    </DataTemplate>
</ResourceDictionary>

我将资源字典添加到我的页面,如下所示:

<Page.Resources>
    <ResourceDictionary Source="ms-appx:///Style/Special.xaml" />
</Page.Resources>

我像这样使用 SpecialRectangle:

<ContentPresenter ContentTemplate="{StaticResource SpecialTemplate}" />

问题:如何更改颜色?

[update] 我试过这个,但它对我不起作用:

<Page.Resources>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ms-appx:///Style/Special.xaml" />
    </ResourceDictionary.MergedDictionaries>
    <SolidColorBrush x:Key="SpecialColor" Color="Red" />
</Page.Resources>

这也不起作用:

<Page.Resources>
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="ms-appx:///Style/Special.xaml" />
        <ResourceDictionary>
            <SolidColorBrush x:Key="SpecialColor" Color="Red" />
        </ResourceDictionary>
    </ResourceDictionary.MergedDictionaries>
</Page.Resources>

谢谢。

【问题讨论】:

    标签: xaml winrt-xaml resourcedictionary staticresource


    【解决方案1】:

    根据条件,您有很多选择 - 主要是

    1. 根据什么改变颜色?
    2. ContentPresenter 在哪里?性能更重要还是开发人员方便/清晰的架构更重要。

    您可以使用模板选择器并使用两个模板而不是一个模板,您可以绑定矩形的Fill,您可以使用VisualStateManager,如果您在@ 中,您可以使用CCC 事件987654325@ 并且想要在没有绑定的情况下获得最佳性能,您也可以简单地遍历可视化树并惹恼一些人。 :)

    【讨论】:

    • 好吧,但是我们需要覆盖SpecialColor StyleSpecialColor 必须在外部 ResourceDictionary 中定义,否则无法构建。但它需要在别处进行定义、定制。
    • 好吧,也许您可​​以将该外部字典合并到您的页面字典中,然后在触发重新加载 UI 以重新评估资源之前将其替换为另一个字典...
    • 我肯定首先尝试过。要么我的语法不正确,要么它不起作用。我已经用语法更新了问题。
    • 不,这行不通,因为这是一个静态资源,所以 Special.xaml 已经将具有键“SpecialColor”的资源评估为来自 Special.xaml 的资源。您需要提供两个具有不同颜色的完整版本的 special.xaml。
    • 如果您有两个名为 Colors.Red.xaml 和 Controls.XAML 的 ResourceDictionaries,并且您想切换到 Colors.Green.XAML,您如何在 App.xaml 中处理这个问题?似乎是一个合理的事情。
    猜你喜欢
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多