You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI中如何根据平台在MainWindow加载对应Content Page?

基于OnPlatform特性实现跨平台页面加载方案

实现步骤

1. 编写MainWindow的XAML布局

直接在XAML中利用OnPlatform特性指定不同平台对应的页面,这是最贴合需求的最优实现:

<Window xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:local="clr-namespace:YourAppNamespace"
        x:Class="YourAppNamespace.MainWindow">
    <Window.Content>
        <OnPlatform x:TypeArguments="View">
            <!-- iOS/Android平台加载MobileWindow -->
            <On Platform="iOS, Android">
                <local:MobileWindow />
            </On>
            <!-- 桌面平台(Windows/MacCatalyst/Tizen)加载DesktopWindow -->
            <On Platform="Windows, MacCatalyst, Tizen">
                <local:DesktopWindow />
            </On>
        </OnPlatform>
    </Window.Content>
</Window>

2. MainWindow后台代码简化处理

后台代码无需额外平台判断逻辑,保持默认结构即可:

namespace YourAppNamespace;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

关键说明

  • 该方案完全依赖XAML的OnPlatform特性实现分支逻辑,符合需求中的优先要求,避免了后台代码的平台判断,结构更清晰易维护。
  • 替换代码中的YourAppNamespace为项目实际的命名空间,确保MobileWindow和DesktopWindow正确继承自ContentPage(或你需要的基类)。
  • 若后续需要调整平台覆盖范围,只需修改On节点的Platform属性值即可。

内容的提问来源于stack exchange,提问作者Maksym Shymchenko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 11:29:51