【初入MAUI】如何添加特定于平台的自定义,2种方式,多种语法

如何添加特定于平台的自定义,2种方式,多种语法

第一种方式:使用 OnPlatform 标记扩展

第一种写法:冗长写法

  1. 打开xaml文件

  2. 使用OnPlatform标记扩展

    举例:

    {

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

    }

如此一来,将 iOS、Android 和 Windows 中页面上的堆积布局的背景颜色分别更改为 Silver、Green 和 Yellow。

第二种写法:简洁写法

  1. 打开xaml文件

  2. 使用OnPlatform标记扩展

    举例:

    {

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

    }

第二种方式:使用 Device 类

只有一种写法

  1. 打开XAML下的隐藏文件

  2. 在InitializeComponent()后,设置属性。

    举例:

    {

     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
    

    }

    如此一来,只会在IOS中将内容下移60点,在其他平台则不会。

总结

微软推荐使用第一种方式的简洁写法,理由是“执行此操作更适合且更方便”。

posted @   王山而瑞  阅读(100)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示