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

如何在MAUI的App.xaml中通过OnIdiom选择加载平板/手机资源字典?

在App.xaml中通过OnIdiom按需加载手机/平板专属资源字典

你可以通过将ResourceDictionary.Source与OnIdiom标记扩展结合的方式,实现根据设备类型(手机/平板)加载对应资源字典的需求,具体写法如下:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
            <ResourceDictionary Source="Resources/Styles/Margins.xaml" />
            <!-- 根据设备类型选择加载对应的尺寸资源字典 -->
            <ResourceDictionary>
                <ResourceDictionary.Source>
                    <OnIdiom x:TypeArguments="x:String">
                        <OnIdiom.Phone>Resources/Styles/FixedSizesMobile.xaml</OnIdiom.Phone>
                        <OnIdiom.Tablet>Resources/Styles/FixedSizesTablet.xaml</OnIdiom.Tablet>
                        <!-- 可选:为其他设备类型设置默认加载项 -->
                        <OnIdiom.Default>Resources/Styles/FixedSizesMobile.xaml</OnIdiom.Default>
                    </OnIdiom>
                </ResourceDictionary.Source>
            </ResourceDictionary>
            <ResourceDictionary Source="Resources/Styles/Styles.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

关键说明:

  • 直接在MergedDictionaries中同时添加两个资源字典会导致后加载的字典覆盖前一个的同名资源,而通过OnIdiom可以确保仅加载当前设备类型对应的字典。
  • OnIdiom需要通过x:TypeArguments="x:String"指定类型,因为Source属性接受字符串路径。
  • 可以通过OnIdiom.Default为未明确指定的设备类型(比如桌面设备)设置默认加载的资源字典。

内容的提问来源于stack exchange,提问作者Andy Donegan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:06:08