Fluent UI Blazor 消费者使用指南,介绍如何在 Blazor 应用中正确使用 Microsoft.FluentUI.AspNetCore.Components(第 4 版)NuGet 包。
关键规则
无需手动引入脚本或样式
该库通过 Blazor 的静态 Web 资源和 JS 初始化器自动加载全部 CSS 与 JS。不要为内核库添加 <script> 或 <link> 标签。
Provider 组件为服务型组件的必需项
以下 Provider 组件必须添加到根布局(例如 MainLayout.razor),对应服务才能工作。缺少时服务调用会静默失败(无报错、无 UI):
<FluentToastProvider />
<FluentDialogProvider />
<FluentMessageBarProvider />
<FluentTooltipProvider />
<FluentKeyCodeProvider />
在 Program.cs 中注册服务
builder.Services.AddFluentUIComponents();
// 或带配置:
builder.Services.AddFluentUIComponents(options =>
{
options.UseTooltipServiceProvider = true; // 默认:true
options.ServiceLifetime = ServiceLifetime.Scoped; // 默认
});
ServiceLifetime 规则:Scoped 用于 Blazor Server / Interactive(默认);Singleton 用于 Blazor WebAssembly 独立模式;Transient 会抛出 NotSupportedException。
图标需要单独的 NuGet 包
dotnet add package Microsoft.FluentUI.AspNetCore.Components.Icons
使用 @using 别名:
@using Icons = Microsoft.FluentUI.AspNetCore.Components.Icons
<FluentIcon Value="@(Icons.Regular.Size24.Save)" />
<FluentIcon Value="@(Icons.Filled.Size20.Delete)" Color="@Color.Error" />
命名模式为 Icons.[Variant].[Size].[Name]。变体有 Regular、Filled;尺寸有 Size12、Size16、Size20、Size24、Size28、Size32、Size48。自定义图片使用 Icon.FromImageUrl("/path/to/image.png")。不要使用基于字符串的图标名——图标是强类型类。
列表组件的绑定模型
FluentSelect<TOption>、FluentCombobox<TOption>、FluentListbox<TOption> 和 FluentAutocomplete<TOption> 的行为不同于 <InputSelect>,它们使用:Items(数据源 IEnumerable<TOption>)、OptionText(Func<TOption, string?> 提取显示文本)、OptionValue(Func<TOption, string?> 提取值字符串)、SelectedOption / SelectedOptionChanged(单选绑定)、SelectedOptions / SelectedOptionsChanged(多选绑定)。
<FluentSelect Items="@countries"
OptionText="@(c => c.Name)"
OptionValue="@(c => c.Code)"
@bind-SelectedOption="@selectedCountry"
Label="Country" />
以下为错误模式,不要使用 InputSelect 的写法:
@* 错误——不要使用 InputSelect 模式 *@
<FluentSelect @bind-Value="@selectedValue">
<option value="1">One</option>
</FluentSelect>
FluentAutocomplete 细节
使用 ValueText(不要用已废弃的 Value)作为搜索输入文本;OnOptionsSearch 是过滤选项的必需回调;默认 Multiple="true"。
<FluentAutocomplete TOption="Person"
OnOptionsSearch="@OnSearch"
OptionText="@(p => p.FullName)"
@bind-SelectedOptions="@selectedPeople"
Label="Search people" />
@code {
private void OnSearch(OptionsSearchEventArgs<Person> args)
{
args.Items = allPeople.Where(p =>
p.FullName.Contains(args.Text, StringComparison.OrdinalIgnoreCase));
}
}
对话框服务模式
不要通过切换 <FluentDialog> 标签的可见性来实现。服务模式如下:
创建一个实现 IDialogContentComponent<TData> 的内容组件:
public partial class EditPersonDialog : IDialogContentComponent<Person>
{
[Parameter] public Person Content { get; set; } = default!;
[CascadingParameter] public FluentDialog Dialog { get; set; } = default!;
private async Task SaveAsync()
{
await Dialog.CloseAsync(Content);
}
private async Task CancelAsync()
{
await Dialog.CancelAsync();
}
}
通过 IDialogService 显示对话框:
[Inject] private IDialogService DialogService { get; set; } = default!;
private async Task ShowEditDialog()
{
var dialog = await DialogService.ShowDialogAsync<EditPersonDialog, Person>(
person,
new DialogParameters
{
Title = "Edit Person",
PrimaryAction = "Save",
SecondaryAction = "Cancel",
Width = "500px",
PreventDismissOnOverlayClick = true,
});
var result = await dialog.Result;
if (!result.Cancelled)
{
var updatedPerson = result.Data as Person;
}
}
便捷对话框:
await DialogService.ShowConfirmationAsync("Are you sure?", "Yes", "No");
await DialogService.ShowSuccessAsync("Done!");
await DialogService.ShowErrorAsync("Something went wrong.");
Toast 通知
[Inject] private IToastService ToastService { get; set; } = default!;
ToastService.ShowSuccess("Item saved successfully");
ToastService.ShowError("Failed to save");
ToastService.ShowWarning("Check your input");
ToastService.ShowInfo("New update available");
FluentToastProvider 参数:Position(默认 TopRight)、Timeout(默认 7000ms)、MaxToastCount(默认 4)。
设计令牌与主题仅在渲染后生效
设计令牌依赖 JS 互操作,不要在 OnInitialized 中设置,应使用 OnAfterRenderAsync。
<FluentDesignTheme Mode="DesignThemeModes.System"
OfficeColor="OfficeColor.Teams"
StorageName="mytheme" />
FluentEditForm 与 EditForm
FluentEditForm 仅在 FluentWizard 步骤内部(逐步验证)需要。常规表单使用标准 EditForm 配合 Fluent 表单组件:
<EditForm Model="@model" OnValidSubmit="HandleSubmit">
<DataAnnotationsValidator />
<FluentTextField @bind-Value="@model.Name" Label="Name" Required />
<FluentSelect Items="@options"
OptionText="@(o => o.Label)"
@bind-SelectedOption="@model.Category"
Label="Category" />
<FluentValidationSummary />
<FluentButton Type="ButtonType.Submit" Appearance="Appearance.Accent">Save</FluentButton>
</EditForm>
为获得 Fluent 样式,请使用 FluentValidationMessage 和 FluentValidationSummary 替代标准 Blazor 验证组件。
参考文件
更详细的专题指引见:安装与配置、布局与导航、数据网格、主题。