XAML共享资源

3

我希望能够实现类似于CSS样式的XAML。我想要创建一个自定义布局用于ContentPage,使得在我的应用程序中的所有页面都可以使用,并且每个平台都有不同的值。

具体来说,我先从自定义填充开始:我试图将以下代码放在我的App.xaml文件中:

<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>

在另一个ContentPage中,我正在进行以下操作,但它不起作用:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
        x:Class="MyApp.LoginScreen" 
        Style="{DynamicResource MyPadding}"
>

自定义的Entry样式没有问题,但是内边距有问题。我得到了错误提示:“SetValue:无法将Xamarin.Forms.OnPlatform`1[Xamarin.Forms.Thickness]转换为类型'Xamarin.Forms.Style'”。我的做法错在哪里了?
1个回答

3
正如错误提示所说,Thickness不是一个Style。请将其更改为:
<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}">

或者

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接