如何改变资源词典颜色运行 [英] How to change Resource Dictionary Color in the runtime

查看:144
本文介绍了如何改变资源词典颜色运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在XAML:

<ResourceDictionary>
    <Color x:Key="BrushColor1">Red</Color>
    <Color x:Key="BrushColor2">Black</Color>

    <LinearGradientBrush x:Key="GradientBrush1" StartPoint="0,0.5" EndPoint="1,0.5">
        <GradientStop Color="{DynamicResource BrushColor2}" Offset="0" />
        <GradientStop Color="{DynamicResource BrushColor1}" Offset="1" />
    </LinearGradientBrush>
</ResourceDictionary>

在C#中:

    public void CreateTestRect()
    {
        Rectangle exampleRectangle = new Rectangle();
        exampleRectangle.Width = 150;
        exampleRectangle.Height = 150;
        exampleRectangle.StrokeThickness = 4;
        exampleRectangle.Margin = new Thickness(350);

        ResourceDictionary resources = this.Resources;
        resources["BrushColor1"] = Colors.Pink;
        resources["BrushColor2"] = Colors.RoyalBlue;
        Brush brush =(Brush)this.FindResource("GradientBrush1");

        exampleRectangle.Fill = brush;
        canvas.Children.Insert(0, exampleRectangle);
    }



如何更改在运行时的色彩元素在C#。

How to change those Color elements in the runtime in C#. The LinearGradientBrush should get changed dynamically?

我希望做这样的事情:

(Color)(this.FindResource("BrushColor1")) = Colors.Pink;



但我失败了。

but I failed.

推荐答案

您可以直接覆盖在资源字典值

You can directly overwrite the value in the resource dictionary.

例如:

ResourceDictionary resources = this.Resources; // If in a Window/UserControl/etc
resources["BrushColor1"] = System.Windows.Media.Colors.Black;



话虽这么说,我通常不建议这样做。相反,我将有两套颜色,每个都有自己的钥匙,并使用一些机制来切换哪种颜色在运行时被分配到你的价值观来代替。这可以让你离开整个逻辑为此在XAML本身。

That being said, I would normally recommend not doing this. Instead, I would have two sets of colors, each with their own key, and use some mechanism to switch which color is assigned to your values at runtime instead. This lets you leave the entire logic for this in the xaml itself.

这篇关于如何改变资源词典颜色运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆