MAUI怎么在XAML里写样式 MAUI Style资源使用教程

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

MAUI怎么在XAML里写样式 MAUI Style资源使用教程-第1张图片-佛山资讯网

MAUI 中的样式(Style)写在 XAML 里,核心是用 ResourceDictionary 定义资源,再通过 Style 设置属性,最后用 StyleIdClass 或类型自动匹配来应用。关键不是“怎么写”,而是“在哪定义、怎么引用、怎么复用”。

在 App.xaml 里全局定义样式

这是最常用的方式,适合全应用统一的外观,比如按钮颜色、字体大小等。打开 App.xaml,在 Application.Resources 下添加:

  • StyleTargetType 指定控件类型(如 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 里:

  • 局部资源优先级高于全局,同名时会覆盖 App.xaml 中的定义
  • 适合快速调整单页 UI,或做 A/B 测试式样式切换
  • 记得用 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>

登录后复制

用 Class 属性批量应用样式(推荐)

MAUI 支持类似 CSS 的 Class 属性,比硬编码 Style="{StaticResource ...}" 更灵活:

标签: css 编码 app c# 重绘

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~