MAUI 中使用 C# Markup 编写 UI,核心是借助 Microsoft.Maui.Controls.Markup(原 Xamarin.Forms.Markup 的演进版)提供的扩展方法,用纯 C# 代码替代 XAML,实现类型安全、可调试、易复用的 UI 构建方式。它不是“强制替代 XAML”,而是提供一种更贴近逻辑、更适合动态/条件化界面的编码风格。
启用 C# Markup 支持
MAUI 6+ 默认已内置基础支持,但需确保项目引用了必要命名空间,并启用扩展方法:
在App.xaml.cs或页面类顶部添加:
using Microsoft.Maui.Controls.Markup;确认
MauiProgram.cs中已调用
builder.UseMauiApp<app>()</app>—— 默认已包含,无需额外配置 若提示找不到
.Background()、
.Children()等方法,请检查是否遗漏 using,或 NuGet 包是否为最新稳定版(.NET 8 SDK + MAUI 8)
从一个 Button 开始:基础语法
对比 XAML 写法:
<button text="点击" backgroundcolor="Blue" clicked="OnClicked"></button>
对应 C# Markup 写法:
new Button()
.Text("点击")
.BackgroundColor(Colors.Blue)
.OnClicked(OnClicked)关键点:
每个扩展方法返回this,支持链式调用 属性名与 XAML 属性基本一致(如
Text、
BackgroundColor),大小写敏感 事件处理用
.OnClicked()、
.OnTextChanged()等,传入方法名或 lambda
构建完整页面:StackLayout + 多控件组合
以一个带标题、输入框和按钮的登录页为例:
public class LoginPage : ContentPage
{
public LoginPage()
{
Content = new VerticalStackLayout()
.Padding(20)
.Children(
new Label().Text("欢迎登录").FontSize(24).HorizontalTextAlignment(TextAlignment.Center),
new Entry().Placeholder("用户名").Margin(0, 16, 0, 8),
new Entry().Placeholder("密码").IsPassword(true).Margin(0, 0, 0, 16),
new Button().Text("登录").BackgroundSource(new SolidColorBrush(Colors.Teal)).HeightRequest(44)
.OnClicked(async _ => await DisplayAlert("提示", "登录中...", "确定"))
);
}
}说明:
.Children()接收多个控件(支持 params),自动添加到布局容器
.Margin()、
.Padding()使用
Thickness语义,支持单值、双值(水平/垂直)、四值(左/上/右/下)
.BackgroundSource()用于设置渐变或图片背景;纯色用
new SolidColorBrush(Colors.XXX)
进阶技巧:绑定、资源与复用
C# Markup 同样支持 MVVM 绑定和样式复用:
绑定:.Bind(Button.TextProperty, nameof(ViewModel.Title))或使用快捷语法
.Bind(x => x.Text, vm => vm.Title)(需安装
Microsoft.Maui.Controls.Markup.Bindings扩展) 样式复用:定义静态扩展方法封装常用样式,例如:
public static T PrimaryButton<t>(this T button) where T : Button => button.BackgroundSource(new SolidColorBrush(Colors.Primary)).TextColor(Colors.White);</t>
然后调用:
new Button().Text("提交").PrimaryButton()
条件渲染:直接用 if/else 或三元表达式构造控件,比如:showHint ? new Label().Text("请输入邮箱") : null,再传入 .Children()
基本上就这些。C# Markup 不复杂但容易忽略细节——重点是理解它是“控件实例 + 链式配置”,而非声明式模板。适合逻辑驱动 UI、A/B 测试分支、运行时动态生成界面等场景。XAML 和 C# Markup 可在同一项目共存,按需选用即可。
