简体   繁体   English

如何从页面中的App.xaml获取颜色值

[英]How to Get a Color Value from App.xaml in a Page

I have declared a color that I will be using a lot in my application, and I would like to be able to call that specific color within a page. 我已经宣布了一种颜色,我将在我的应用程序中大量使用,我希望能够在页面中调用该特定颜色。 This color will most likely be used in in XAML as well as code behind. 这种颜色最有可能用于XAML以及后面的代码。 In App.xaml I have 在App.xaml我有

<Color x:Name="Blue" A="255" R="35" G="85" B="145"/>

But how would I call this in my Page's UI and code behind? 但是我如何在我的Page的UI和代码中调用它呢?

Actually to note, the above setting a color in App.xaml gives a debugging error on startup? 实际上要注意,上面在App.xaml中设置颜色会在启动时出现调试错误?

public App()
    {
        // Standard XAML initialization
        InitializeComponent(); //XamlParseException occurs here

        ...
    }

EDIT** 编辑**

Update for SolidColorBrush not working SolidColorBrush更新无法正常工作

I have a Slider control and two ToggleSwitch controls declared in XAML, and I wish to change the Slider foreground in XAML and change the ToggleSwitch controls in code behind. 我有一个Slider控件和两个在XAML中声明的ToggleSwitch控件,我希望在XAML中更改Slider前景并更改后面代码中的ToggleSwitch控件。 Neither is working 两者都不起作用

App.xaml App.xaml中

<Color x:Key="ThemeColorBlue" A="255" R="35" G="85" B="145"/>
<SolidColorBrush x:Key="ThemeBrushBlue" Color="{StaticResource ThemeColorBlue}"/>

and so when attempting to change the Slider control foreground in XAML I get no errors using 因此,当尝试在XAML中更改Slider控件前景时,我没有使用错误

Foreground="{StaticResource ThemeBrushBlue}"

but when changing the ToggleSwitch foreground in code behind I get an error stating Cannot implicitly convert type 'object' to 'System.Windows.Media.Brush' 但是在后面的代码中更改ToggleSwitch前景时我得到一个错误说明Cannot implicitly convert type 'object' to 'System.Windows.Media.Brush'

this.ToggleSwitch.SwitchForeground = Application.Current.Resources["ThemeBrushBlue"];

You would usually add the Color to Application.Resources with a Key instead of a Name : 您通常会使用Key而不是Name将Color添加到Application.Resources

<Application.Resources>
    <Color x:Key="Blue" A="255" R="35" G="85" B="145"/>
</Application.Resources>

Now you can access it in XAML as StaticResource , eg: 现在您可以在XAML中以StaticResource访问它,例如:

<SolidColorBrush Color="{StaticResource Blue}"/>

or in code like this: 或者像这样的代码:

var color = (Color)Application.Current.Resources["Blue"];

I think the problem is 我认为问题是

<SolidColorBrush x:Key="ThemeBrushBlue" Color="{StaticResource ThemeColorBlue}"/>

Just repeat the color and it should work: 只需重复颜色,它应该工作:

<SolidColorBrush x:Key="ThemeBrushBlue" Color="#235591"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM