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

来源:这里教程网 时间:2026-02-21 17:34:40 作者:

MAUI 中的样式(Style)写在 XAML 里,核心是用

ResourceDictionary
定义资源,再通过
Style
设置属性,最后用
StyleId
Class
或类型自动匹配来应用。关键不是“怎么写”,而是“在哪定义、怎么引用、怎么复用”。

在 App.xaml 里全局定义样式

这是最常用的方式,适合全应用统一的外观,比如按钮颜色、字体大小等。打开

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

局部资源优先级高于全局,同名时会覆盖 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 ...}"
更灵活:

在资源中定义样式时加上
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 属性
在 C# 中用
Resources["KeyName"] as Style
获取并赋值
注意:修改后需触发 UI 刷新,通常设置新 Style 后自动重绘

小技巧:把不同主题的样式集打包成 ResourceDictionary,运行时替换

Application.Resources.MergedDictionaries
实现换肤。

基本上就这些。MAUI 的样式机制和 WPF/UWP 一脉相承,但更精简。别堆砌太多嵌套 Style,优先用 Class + 全局资源,维护起来最省心。

相关推荐