简体   繁体   中英

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>

您可以这样访问:

Application.Current.Resources["TextColor1"];

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

The solution proposed here ( Application.Current.Resources["TextColor1"];<\/code> ) works only if you don't have ResourceDictionary.MergedDictionaries<\/code> , otherwise, you need the following approach:

// helper method
private object GetResourceValue(string keyName)
{
    // Search all dictionaries
    if (Xamarin.Forms.Application.Current.Resources.TryGetValue(keyName, out var retVal)) {}
    return retVal;
}

这肯定会更好,尤其是在您使用 MergedDictionaries 时

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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