How to access resource values in MAUI .NET 8?

Chinmay Dole 120 Reputation points
2024-06-18T06:45:32.6166667+00:00

Hello,

In Xamarin Forms I was accessing dynamic resources from the App.xaml.cs file using the below code

// On ViewModel

var thickness = Application.Current.Resources["BorderThickness"].GetType().GetProperty("Android").GetValue(size, null);

//App.xaml.cs

<OnPlatform x:TypeArguments="Thickness" x:Key="BorderThickness">

<On Platform="iOS" Value="0,20,0,0" />

<On Platform="Android" Value="5, 10" />

</OnPlatform>

// On ViewModel

var thickness = Application.Current.Resources["BorderThickness"].GetType().GetProperty("Android")

.GetValue(Application.Current.Resources["BorderThickness"], null);

The App crashes when I try to get the value in MAUI .NET 8. How to achieve this in .NET MAUI?

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,176 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 71,836 Reputation points Microsoft Vendor
    2024-06-18T07:35:48.8+00:00

    Hello,

    The App crashes when I try to get the value in MAUI .NET 8. How to achieve this in .NET MAUI?

    You can do it by Application.Current.Resources.TryGetValue like following code.

    var res =Application.Current.Resources.TryGetValue("BorderThickness", out object r2) ;
     
          if (res)
          {
              Microsoft.Maui.Controls.OnPlatform<Microsoft.Maui.Thickness> resThickness = (Microsoft.Maui.Controls.OnPlatform<Microsoft.Maui.Thickness>)r2;
             var AndroidPlatformsThinkness = resThickness.Platforms[1].Value;
        
          }
    

    Here is a document about:Access resources by key from code

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful