Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML shared resources

I am trying to implement the XAML equivalent of CSS styles. I want to create a custom layout for ContentPage that I can use in all pages of my app, and will have a different value for each platform.

Specifically I am starting with custom padding: I am trying to place this code in my App.xaml file:

<Application.Resources>
    <ResourceDictionary>
        <OnPlatform x:Key="MyPadding"
             x:TypeArguments="Thickness"
            iOS="0, 20, 0, 0"
            Android="0, 0, 0, 0"/>

        <Style
            x:Key="labelGreen"
            TargetType="Entry">

            <Setter
                Property="TextColor" 
                Value="Green"/>
        </Style>

    </ResourceDictionary>
</Application.Resources>

In a separate ContentPage, I am doing the following, but it does not work:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
        x:Class="MyApp.LoginScreen" 
        Style="{DynamicResource MyPadding}"
>

The custom Entry style works fine. But the padding does not. I get the error: "SetValue: Can not convert Xamarin.Forms.OnPlatform`1[Xamarin.Forms.Thickness] to type 'Xamarin.Forms.Style'"

What am I doing wrong?

like image 479
Bassman Avatar asked Dec 11 '25 10:12

Bassman


1 Answers

Just as error says, Thickness is not a Style. Change it to:

<Application.Resources>
    <ResourceDictionary>
        <OnPlatform x:Key="MyPadding"
             x:TypeArguments="Thickness"
            iOS="0, 20, 0, 0"
            Android="0, 0, 0, 0"/>

        <Style
            x:Key="pageStyle"
            TargetType="ContentPage">

            <Setter
                Property="Padding" 
                Value="{StaticResource MyPadding}"/>
        </Style>

        <Style
            x:Key="labelGreen"
            TargetType="Entry">

            <Setter
                Property="TextColor" 
                Value="Green"/>
        </Style>

    </ResourceDictionary>
</Application.Resources>


<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
        x:Class="MyApp.LoginScreen" 
        Style="{StaticResource pageStyle}">

OR

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
        x:Class="MyApp.LoginScreen" 
        Padding="{StaticResource MyPadding}">
like image 182
Daniel Luberda Avatar answered Dec 13 '25 00:12

Daniel Luberda



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!