Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. In App.xaml I have

<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?

Actually to note, the above setting a color in App.xaml gives a debugging error on startup?

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

        ...
    }

EDIT**

Update for SolidColorBrush not working

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. Neither is working

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

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'

this.ToggleSwitch.SwitchForeground = Application.Current.Resources["ThemeBrushBlue"];
like image 547
Matthew Avatar asked Nov 24 '13 16:11

Matthew


2 Answers

You would usually add the Color to Application.Resources with a Key instead of a Name:

<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, e.g.:

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

or in code like this:

var color = (Color)Application.Current.Resources["Blue"];
like image 126
Clemens Avatar answered Oct 08 '22 19:10

Clemens


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"/>
like image 35
Igor Kulman Avatar answered Oct 08 '22 19:10

Igor Kulman