Wednesday, July 6, 2022

Resources in .Net MAUI

 A resource is like a symbolic constant from a programming language. You define it in one place and reference it everywhere you need it. Your code will be easier to read because you use a descriptive name instead of a "magic" value. If you need to change the value, you only need to update the definition.

Every .NET MAUI XAML page has a property named Resources that can hold a ResourceDictionary object. The property is null by default, so you'll need to create a dictionary instance before you can use it. 

XML

<ContentPage.Resources> <ResourceDictionary> <Color x:Key="PageControlTextColor">Blue</Color> </ResourceDictionary> </ContentPage.Resources>

...

...

<Label TextColor="{StaticResource PageControlTextColor}" ... />


Set platform-specific values for a resource

<ContentPage.Resources> <OnPlatform x:Key="textColor" x:TypeArguments="Color"> <On Platform="iOS" Value="Silver" /> <On Platform="Android" Value="Green" /> <On Platform="WinUI" Value="Yellow" /> <On Platform="MacCatalyst" Value="Pink" /> </OnPlatform> </ContentPage.Resources> ... <Label TextColor="{StaticResource textColor}" ... />


Dynamic Resources

DynamicResource is another mark-up extension for looking up resources in a resource dictionary. It's similar to StaticResource in that it does a dictionary lookup when the target object is created. But it also listens for changes to the resource in the dictionary. If the resource value in the dictionary changes, DynamicResource automatically updates the UI.

Example:

XML

<ContentPage ...>

<ContentPage.Resources> <Color x:Key="PanelBackgroundColor">Blue</Color> </ContentPage.Resources> <StackLayout BackgroundColor="{DynamicResource PanelBackgroundColor}"> ... </StackLayout> </ContentPage>

c#

this.Resources["PanelBackgroundColor"] = Colors.Green;


No comments:

Post a Comment

Open default email app in .NET MAUI

Sample Code:  if (Email.Default.IsComposeSupported) {     string subject = "Hello!";     string body = "Excellent!";    ...