Create your own system colors

Basically, how can I create my own set of colors in a static class or such that I can do something like this:

What exists :

<Setter ... Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>

What I want :

<Setter ... Value="{DynamicResource {x:Static MyColors.Color1}}"/>
+3
source share
3 answers

Resource keys can be any, so you can use Colorboth the key and value at the same time:

public static class MyColors
{
    static MyColors()
    {
        App.Current.Resources.Add(MyHighlightColorKey, MyHighlightColorKey);
    }

    public static readonly Color MyHighlightColorKey = Color.FromArgb(255, 0, 88, 0);
}

The static constructor adds color, using itself as a key to application resources.

(SystemColors SystemResourceKeys , ( ), ResourceKey, )

:

<TextBox>
    <TextBox.Background>
        <SolidColorBrush Color="{DynamicResource {x:Static local:MyColors.MyHighlightColorKey}}"/>
    </TextBox.Background>
</TextBox>

, :

<Window.Resources>
    <Color x:Key="{x:Static local:MyColors.MyHighlightColorKey}" A="255" R="255" G="0" B="0"/>
</Window.Resources>

: , ( , ):

static MyColors()
{
    FieldInfo[] keyFieldInfoArray = typeof(MyColors).GetFields();
    foreach (var keyFieldInfo in keyFieldInfoArray)
    {
        object value = keyFieldInfo.GetValue(null);
        App.Current.Resources.Add(value, value);
    }
}
+5

, . , - ...

public struct MyColors
{
    public static Brush Color1
    {
        get { return Brushes.Red; } // or whatever you like
    }
    public static Brush Color2
    {
        get { return Brushes.Blue; }
    }
}

XAML :

"{x:Static local:MyColors.Color1}"

10 , DynamicResource, . - , ( ), :)

+4

. :

public class MyColors
{
    public static string Color1{ get{return "Color1Key";}}
}

, , App.xaml:

<Application ...>
    <Application.Resources>
        <Color x:Key="Color1Key">#FF969696</Color>
    </Application.Resources>
</Application>

. , , :

<Setter ... Value="{DynamicResource Color1Key}"/>

( , <Color x:Key="{x:Static MyColors.Color1}">#FF969696</Color>, ...)

( , x:Static , MyColors , {x:Static local:MyColors.Color1})

+1
source

Source: https://habr.com/ru/post/1739120/


All Articles