Thursday, June 30, 2022

Using the Device class and OnPlatform mark-up extension in .Net MAUI

The DeviceInfo class is a utility class that provides device-specific information for the device on which your app is running. It exposes this information through a set of properties. The most important property is DeviceInfo.Platform. The property returns a string indicating the type of device currently in use; "Android", "iOS", "WinUI", or "macOS".

Example:

MyStackLayout.Padding = DeviceInfo.Platform == DevicePlatform.iOS ? new Thickness(30, 60, 30, 30) // Shift down by 60 points on iOS only : new Thickness(30); // Set the default margin to be 30 points


.NET MAUI XAML provides the OnPlatform mark-up extension that enables you to detect the runtime platform from within in your XAML code. You apply this mark-up extension as part of the XAML code that sets a property value. The extension requires you to provide the type of the property, together with a series of On Platform blocks in which you set the value of the property according to the platform.

Example:

Sample 1:

<VerticalStackLayout> <VerticalStackLayout.Padding> <OnPlatform x:TypeArguments="Thickness"> <On Platform="iOS" Value="30,60,30,30" /> <On Platform="Android" Value="30" /> <On Platform="WinUI" Value="30" /> </OnPlatform> </VerticalStackLayout.Padding> ... </VerticalStackLayout>

Sample 2:

<VerticalStackLayout Padding="{OnPlatform iOS='30,60,30,30', Default='30'}"> <!--XAML for other controls goes here --> </VerticalStackLayout>

Sample 3:

<VerticalStackLayout> ... <VerticalStackLayout.BackgroundColor> <OnPlatform x:TypeArguments="Color"> <On Platform="iOS" Value="Silver" /> <On Platform="Android" Value="Green" /> <On Platform="WinUI" Value="Yellow" /> </OnPlatform> </VerticalStackLayout.BackgroundColor> ... </VerticalStackLayout>

Sample 4:

<VerticalStackLayout BackgroundColor="{OnPlatform WinUI=Yellow, iOS=Silver, Android=Green}"> ... </VerticalStackLayout>


No comments:

Post a Comment

Open default email app in .NET MAUI

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