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
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
You can access like this:
Application.Current.Resources["TextColor1"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With