MAUI样式核心是ResourceDictionary定义、Style设置属性、Class/StyleId/类型匹配应用;全局样式在App.xaml中定义,局部样式在页面或控件Resources中定义,推荐用Class批量应用,支持BasedOn继承与动态换肤。

MAUI 中的样式(Style)写在 XAML 里,核心是用 ResourceDictionary 定义资源,再通过 Style 设置属性,最后用 StyleId 或 Class 或类型自动匹配来应用。关键不是“怎么写”,而是“在哪定义、怎么引用、怎么复用”。
这是最常用的方式,适合全应用统一的外观,比如按钮颜色、字体大小等。打开 App.xaml,在 Application.Resources 下添加:
Style 的 TargetType 指定控件类型(如 Button),它会自动作用于所有该类型控件x:Key 命名样式,配合 Style="{StaticResource KeyName}" 手动引用BasedOn 继承已有样式,避免重复写属性示例:
<Application.Resources><br> <ResourceDictionary><br> <Style x:Key="PrimaryButton" TargetType="Button"><br> <Setter Property="BackgroundColor" Value="#007AFF" /><br> <Setter Property="TextColor" Value="White" /><br> <Setter Property="FontSize" Value="16" /><br> </Style><br> <Style TargetType="Button" BasedOn="{StaticResource PrimaryButton}"><br> <Setter Property="CornerRadius" Value="8" /><br> </Style><br> </ResourceDictionary><br></Application.Resources>如果某页的样式只用一次或不希望影响其他页面,可以放在 ContentPage.Resources 或某个布局的 Resources 里:
ResourceDictionary 包裹,否则会报错示例(在 Page 根节点内):
<ContentPage.Resources><br> <ResourceDictionary><br> <Style x:Key="SmallLabel" TargetType="Label"><br> <Setter Property="FontSize" Value="12" /><br> <Setter Property="TextColor" Value="#666" /><br> </Style><br> </ResourceDictionary><br></ContentPage.Resources>
MAUI 支持类似 CSS 的 Class 属性,比硬编码 Style="{StaticResource ...}" 更灵活:
Class="name",而不是 x:Key
Class="name" 即可绑定,支持多个类用空格分隔:Class="primary large-button"
TargetType 和 Class
示例:
<Style Class="outline-button" TargetType="Button"><br> <Setter Property="BackgroundColor" Value="Transparent" /><br> <Setter Property="BorderColor" Value="#007AFF" /><br> <Setter Property="BorderWidth" Value="2" /><br></Style>
然后在 Button 上写:<button class="outline-button" text="点击我"></button>
样式本身不能直接改,但可以通过绑定或代码切换整个 Style 引用:
Style 属性绑定一个 Style 类型的 ViewModel 属性Resources["KeyName"] as Style 获取并赋值小技巧:把不同主题的样式集打包成 ResourceDictionary,运行时替换 Application.Resources.MergedDictionaries 实现换肤。
基本上就这些。MAUI 的样式机制和 WPF/UWP 一脉相承,但更精简。别堆砌太多嵌套 Style,优先用 Class + 全局资源,维护起来最省心。
以上就是MAUI怎么在XAML里写样式 MAUI Style资源使用教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号