Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way I can access a static resource in my C# code?

In my App.XAML I have this:

<Application xmlns:converters="clr-namespace:Japanese" xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Japanese.App">
<Application.Resources>
        <Color x:Key="TextColor1">#123456</Color>

I can access this value in XAML like this:

<Style TargetType="Label">
        <Setter Property="TextColor" Value="{StaticResource TextColor1}" />
</Style>

But is there also a way that I can access this in my back end C#

vm.C1BtnLabelTextColor = phrase.C1 == true ? Color.FromHex("#123456") : Color.FromHex("#0000FF");

For example here I would like to replace:

Color.FromHex("#123456")

with the value of the StaticResource

like image 734
Alan2 Avatar asked Oct 06 '18 08:10

Alan2


2 Answers

ResourceDictionary is a repository for resources that are used by a Xamarin.Forms application. Typical resources that are stored in a ResourceDictionary include styles, control templates, data templates, colors, and converters.

In XAML, resources that are stored in a ResourceDictionary can then be retrieved and applied to elements by using the StaticResource markup extension. In C#, resources can also be defined in a ResourceDictionary and then retrieved and applied to elements by using a string-based indexer. However, there's little advantage to using a ResourceDictionary in C#, as shared objects can simply be stored as fields or properties, and accessed directly without having to first retrieve them from a dictionary.

In short: ResourceDictionary is a Dictionary.
To read a value from a Dictionary you have to provide a Key. In your case the Key is "TextColor1". So using C# here is how you could read the value from Application.Resources:

var txtColor1 = (Color) Application.Current.Resources["TextColor1"];

Please note that you have to cast the returned value to a desired type, thats because the Dictionary is "generic".

You could also create an Extension Method if you have to reuse it in your project.

Source: Official documentation

like image 172
EvZ Avatar answered Sep 20 '22 17:09

EvZ


You can access like this:

Application.Current.Resources["TextColor1"];
like image 29
Bruno Caceiro Avatar answered Sep 17 '22 17:09

Bruno Caceiro