fluentui-blazor

fluentui-blazor

熱門

在 Blazor 應用程式中使用 Microsoft Fluent UI Blazor 元件庫(Microsoft.FluentUI.AspNetCore.Components NuGet 套件)的指南。當使用者正在建置使用 Fluent UI 元件的 Blazor 應用程式、設定程式庫、使用 FluentButton、FluentDataGrid、FluentDialog、FluentToast、FluentNavMenu、FluentTextField、FluentSelect、FluentAutocomplete、FluentDesignTheme 或任何以「Fluent」為前綴的元件時,請使用此指南。此外,在排解缺少提供者、JS 互操作問題或主題設定問題時,也請使用此指南。

3.6萬星標
4556分支
更新於 2026/7/13
SKILL.md
唯讀
名稱
fluentui-blazor
描述

在 Blazor 應用程式中使用 Microsoft Fluent UI Blazor 元件庫(Microsoft.FluentUI.AspNetCore.Components NuGet 套件)的指南。當使用者正在建置使用 Fluent UI 元件的 Blazor 應用程式、設定程式庫、使用 FluentButton、FluentDataGrid、FluentDialog、FluentToast、FluentNavMenu、FluentTextField、FluentSelect、FluentAutocomplete、FluentDesignTheme 或任何以「Fluent」為前綴的元件時,請使用此指南。此外,在排解缺少提供者、JS 互操作問題或主題設定問題時,也請使用此指南。

Fluent UI Blazor — 消費者使用指南

本技能教導如何在 Blazor 應用程式中正確使用 Microsoft.FluentUI.AspNetCore.Components (第 4 版) NuGet 套件。

重要規則

1. 不需要手動加入 <script><link> 標籤

此程式庫會透過 Blazor 的靜態 Web 資產和 JS 初始化程式自動載入所有 CSS 和 JS。切勿告訴使用者為核心程式庫加入 <script><link> 標籤。

2. 提供者元件是服務型元件的必要條件

這些提供者元件必須加入根配置(例如 MainLayout.razor),其對應的服務才能正常運作。若缺少它們,服務呼叫會無聲失敗(沒有錯誤訊息,也沒有 UI 顯示)。

<FluentToastProvider />
<FluentDialogProvider />
<FluentMessageBarProvider />
<FluentTooltipProvider />
<FluentKeyCodeProvider />

3. 在 Program.cs 中註冊服務

builder.Services.AddFluentUIComponents();

// 或搭配設定:
builder.Services.AddFluentUIComponents(options =>
{
    options.UseTooltipServiceProvider = true;  // 預設值:true
    options.ServiceLifetime = ServiceLifetime.Scoped; // 預設值
});

ServiceLifetime 規則:

  • ServiceLifetime.Scoped — 適用於 Blazor Server / Interactive(預設)
  • ServiceLifetime.Singleton — 適用於獨立 Blazor WebAssembly
  • ServiceLifetime.Transient會擲回 NotSupportedException

4. 圖示需要額外的 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]

  • 變體:RegularFilled
  • 尺寸:Size12Size16Size20Size24Size28Size32Size48

自訂圖片:Icon.FromImageUrl("/path/to/image.png")

切勿使用字串型別的圖示名稱 — 圖示是強型別的類別。

5. 清單元件的繫結模型

FluentSelect<TOption>FluentCombobox<TOption>FluentListbox<TOption>FluentAutocomplete<TOption> 的運作方式不同於 <InputSelect>。它們使用:

  • Items — 資料來源 (IEnumerable<TOption>)
  • OptionTextFunc<TOption, string?> 用來擷取顯示文字
  • OptionValueFunc<TOption, string?> 用來擷取值字串
  • SelectedOption / SelectedOptionChanged — 用於單選繫結
  • SelectedOptions / SelectedOptionsChanged — 用於多選繫結
<FluentSelect Items="@countries"
              OptionText="@(c => c.Name)"
              OptionValue="@(c => c.Code)"
              @bind-SelectedOption="@selectedCountry"
              Label="Country" />

不是像這樣(錯誤模式):

@* 錯誤 — 不要使用 InputSelect 模式 *@
<FluentSelect @bind-Value="@selectedValue">
    <option value="1">One</option>
</FluentSelect>

6. 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));
    }
}

7. 對話方塊服務模式

不要切換 <FluentDialog> 標籤的可見性。 服務模式如下:

  1. 建立一個實作 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();
    }
}
  1. 透過 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.");

8. 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(預設 7000 毫秒)、MaxToastCount(預設 4)。

9. 設計權杖和主題僅在轉譯後生效

設計權杖依賴 JS 互操作。切勿在 OnInitialized 中設定它們 — 請使用 OnAfterRenderAsync

<FluentDesignTheme Mode="DesignThemeModes.System"
                   OfficeColor="OfficeColor.Teams"
                   StorageName="mytheme" />

10. 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>

請使用 FluentValidationMessageFluentValidationSummary 取代標準的 Blazor 驗證元件,以獲得 Fluent 樣式。

參考檔案

如需特定主題的詳細指引,請參閱: