Taoffi's blog

prisonniers du temps

Xamarin forms: Access your app resources in code

 

 

We now know how to create an App.xaml file (see this post) to define application resources.

To access these resources in xaml, we simply use {StaticResource yourResourceKey} or {DynamicResource yourResourceKey} (you can know more about StaticResource and DynamicResource, and which one to choose Here)

 

Still so often you need to access these resources in your code and that is quite simple:

You may define a static helper that can do this whenever needed:

 

public static object FindResource(string resourceKey)
{
    if(string.IsNullOrEmpty(resourceKey))
        return null;

        return Application.Current.Resources.FirstOrDefault(r => r.Key == resourceKey);
}

 

Now, you can more easily get an application resource by its key.

Let us also write a similar method that can extract this type of resource according to the OS on which the application is running using defined OnPlatform resource:

 

First a generic method that returns a per-Type OnPlatform value:

 

public static T GetPlatformValue<T>(OnPlatform<T> onplatformObjects) where T : class
{
    TargetPlatform    currentOs    = Device.OS;
    T            obj    = onplatformObjects == null
                            ? null
                            : currentOs == TargetPlatform.Android
                                ? onplatformObjects.Android
                                    : currentOs == TargetPlatform.iOS
                                        ? onplatformObjects.iOS
                                            : onplatformObjects.WinPhone;
    return obj;

}

 

Now, to get a device-dependent string defined in an OnPlatform resource with a specified key, we can write:

 

 

public static string FindOnPlatFormStringResource(string resourceKey)
{
    return (string.IsNullOrEmpty(resourceKey)) ? null
                : GetPlatformValue<string>(FindResource(resourceKey)
                    as OnPlatform<string>);
}

 

Putting these helper methods inside a static helper class would be a good thing (for all projects)!

Comments are closed