在 Avalonia 開發中,導航功能是構建多頁面應用的核心需求。Avalonia 無需依賴第三方庫,僅通過內置控件與 MVVM 模式即可實現靈活的頁面切換。本文將以 “基礎導航” 為核心,從 ViewModel 與 View 設計、導航邏輯實現,到樣式美化與響應式交互,完整拆解一個多頁面 Avalonia 應用的開發流程。
一、核心原理:Avalonia 導航的實現邏輯
Avalonia 實現導航的核心思路是?“控件綁定 + 視圖模型切換”:
- 核心控件:使用?
TransitioningContentControl
?作為頁面容器,該控件支持內容切換時的過渡效果,且可直接綁定到 ViewModel 中的屬性。 - 狀態管理:在主視圖模型(如?
MainWindowViewModel
)中定義?_currentPage
?屬性(類型為?ViewModelBase
),通過更新該屬性的值,觸發?TransitioningContentControl
?加載對應的視圖。 - View-ViewModel 匹配:借助 Avalonia 的?
ViewLocator
(通常在項目初始化時自動配置),框架會根據?_currentPage
?的具體 ViewModel 類型,自動匹配并加載對應的 View(視圖)。
二、分步實現:從 ViewModel 到 View 的開發
1. 定義頁面 ViewModel
首先創建兩個業務頁面的 ViewModel(繼承自項目基礎類?ViewModelBase
),分別對應 “顏色列表頁” 和 “關于頁”。
(1)ColorsViewModel:顏色列表視圖模型
該 ViewModel 負責加載系統顏色、處理顏色數據轉換(如 RGB 轉 CMYK),并通過響應式命令觸發數據初始化。
using Avalonia.Data.Converters;
using Avalonia.Media;
using ReactiveUI.SourceGenerators;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;namespace BasicRoutingExample.ViewModels
{public partial class ColorsViewModel : ViewModelBase{// 響應式屬性:當前選中的顏色名稱與顏色值[Reactive]private string? _colorName;[Reactive]private Color? _color;// 顏色轉換器:將 Color 類型轉為 CMYK 格式字符串(靜態屬性,直接復用)public static FuncValueConverter<Color, string> ToCMYK { get; } = new(color =>{double r = color.R / 255.0;double g = color.G / 255.0;double b = color.B / 255.0;double k = 1 - Math.Max(Math.Max(r, g), b);double C = k < 1 ? (1 - r - k) / (1 - k) : 0;double M = k < 1 ? (1 - g - k) / (1 - k) : 0;double Y = k < 1 ? (1 - b - k) / (1 - k) : 0;return $"C={Math.Round(C * 100, 1)}% M={Math.Round(M * 100, 1)}% Y={Math.Round(Y * 100, 1)}% K={Math.Round(k * 100, 1)}%";});// 顏色列表數據源public ObservableCollection<ColorsViewModel> Colors { get; } = [];// 無參構造函數(用于框架實例化)public ColorsViewModel() { }// 響應式命令:初始化顏色列表(加載 Avalonia 內置顏色)[ReactiveCommand]private void Init(){// 反射獲取 Avalonia.Media.Colors 中的所有靜態顏色屬性var colorProperties = typeof(Colors).GetProperties(BindingFlags.Static | BindingFlags.Public).Where(p => p.PropertyType == typeof(Color));foreach (var property in colorProperties){if (property.GetValue(null) is Color color){Colors.Add(new ColorsViewModel{Color = color,ColorName = property.Name // 顏色名稱(如 "Red"、"Blue")});}}}}
}
2)AboutViewModel:關于頁視圖模型
該 ViewModel 主要提供應用基礎信息(名稱、版本、描述),通過反射獲取程序集信息。
using System.Reflection;namespace BasicRoutingExample.ViewModels
{public partial class AboutViewModel : ViewModelBase{// 應用名稱(從當前程序集獲取)public string? AppName => Assembly.GetExecutingAssembly().GetName().Name;// 應用版本(從當前程序集獲取)public string? Version => Assembly.GetExecutingAssembly().GetName()?.Version?.ToString();// 應用描述信息public string Message => "這是基于 Avalonia 框架開發的應用,集成 ReactiveUI 實現響應式交互。";}
}
2. 設計頁面 View(視圖)
View 采用 XAML 編寫,通過數據綁定關聯對應的 ViewModel,實現 “數據驅動視圖”。
(1)ColorsView:顏色列表視圖
通過?ItemsControl
?展示顏色列表,搭配?ColorToHexConverter
?和自定義的?ToCMYK
?轉換器,實現顏色的多格式展示。
<UserControl xmlns="https://github.com/avaloniaui"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:vm="using:BasicRoutingExample.ViewModels"xmlns:b="using:BasicRoutingExample.Behaviors"xmlns:cv="using:Avalonia.Controls.Converters"mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="560"x:DataType="vm:ColorsViewModel"<!-- 頁面加載時執行 Init 命令,初始化顏色數據 -->b:LoadedBehavior.ExecuteCommandOnLoaded="{Binding InitCommand}"x:Class="BasicRoutingExample.Views.ColorsView"> <!-- 資源定義:顏色轉 16 進制字符串轉換器 --><UserControl.Resources><cv:ColorToHexConverter x:Key="ColorToHex" AlphaPosition="Leading" IsAlphaVisible="False"/> </UserControl.Resources><!-- 布局:頂部標題 + 滾動列表 --><Grid RowDefinitions="Auto,*"><!-- 標題:顯示顏色總數 --><TextBlock Text="{Binding Colors.Count, StringFormat='Avalonia 系統顏色 ({0}種)'}" FontSize="18" Margin="5"/><!-- 滾動列表:展示所有顏色 --><ScrollViewer Grid.Row="1"><ItemsControl ItemsSource="{Binding Colors}"><ItemsControl.ItemTemplate><DataTemplate><StackPanel Orientation="Horizontal" Spacing="10" Margin="5"><!-- 顏色預覽塊 --><Rectangle Width="300" Height="30"><Rectangle.Fill><SolidColorBrush Color="{Binding Color}"/></Rectangle.Fill></Rectangle><!-- 顏色名稱 --><TextBlock Text="{Binding ColorName}" Width="110"/><!-- 16 進制顏色值(使用內置轉換器) --><TextBlock Text="{Binding Color, Converter={StaticResource ColorToHex}, ConverterParameter={x:True}}" Width="80"/><!-- CMYK 顏色值(使用 ViewModel 中的靜態轉換器) --><TextBlock Text="{Binding Color, Converter={x:Static vm:ColorsViewModel.ToCMYK}}"/></StackPanel></DataTemplate></ItemsControl.ItemTemplate></ItemsControl></ScrollViewer></Grid>
</UserControl>
(2)AboutView:關于頁視圖
簡潔展示應用名稱、版本和描述,通過網格布局實現內容對齊。
<UserControl xmlns="https://github.com/avaloniaui"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:vm="using:BasicRoutingExample.ViewModels"mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="560"x:DataType="vm:AboutViewModel"x:Class="BasicRoutingExample.Views.AboutView"> <!-- 布局:兩行網格,分別展示“應用信息”和“描述” --><Grid RowDefinitions="Auto,Auto"><!-- 應用名稱 + 版本 --><StackPanel Orientation="Horizontal" Spacing="5" Grid.Row="0"><TextBlock Text="{Binding AppName}" FontWeight="Bold" FontSize="24"/><TextBlock Text="{Binding Version}" FontSize="20"/></StackPanel><!-- 應用描述 --><TextBlock Text="{Binding Message}" Grid.Row="1" FontSize="18"Margin="0,10,0,0"/></Grid>
</UserControl>
3. 實現主窗口導航邏輯
主窗口的 ViewModel(MainWindowViewModel
)負責管理頁面切換狀態,通過響應式命令觸發導航,并通過屬性監聽實現按鈕 “選中態” 同步。
MainWindowViewModel:導航核心邏輯
using Microsoft.Extensions.DependencyInjection;
using ReactiveUI;
using ReactiveUI.SourceGenerators;
using System.Reactive.Linq;namespace BasicRoutingExample.ViewModels
{public partial class MainWindowViewModel : ViewModelBase{// 核心導航屬性:當前顯示的頁面 ViewModel[Reactive]private ViewModelBase? _currentPage; // 導航命令:跳轉到“顏色列表頁”[ReactiveCommand]private void GotoColors(){// 避免重復切換同一頁面if (CurrentPage is not ColorsViewModel){// 從 IOC 容器獲取 ColorsViewModel 實例CurrentPage = App.Current.Services?.GetRequiredService<ColorsViewModel>();}}// 導航命令:跳轉到“關于頁”[ReactiveCommand]private void GotoAbout(){// 避免重復切換同一頁面if (CurrentPage is not AboutViewModel){// 從 IOC 容器獲取 AboutViewModel 實例CurrentPage = App.Current.Services?.GetRequiredService<AboutViewModel>();}}// 構造函數:初始化默認頁面,并監聽頁面切換狀態public MainWindowViewModel(){// 初始頁面設為“顏色列表頁”CurrentPage = App.Current.Services?.GetRequiredService<ColorsViewModel>();// 監聽 CurrentPage 變化,同步“顏色頁選中態”_isColorsPage = this.WhenAnyValue(x => x.CurrentPage).Select(x => x?.GetType() == typeof(ColorsViewModel)).ToProperty(this, x => x.IsColorsPage);// 監聽 CurrentPage 變化,同步“關于頁選中態”_isAboutPage = this.WhenAnyValue(x => x.CurrentPage).Select(x => x?.GetType() == typeof(AboutViewModel)).ToProperty(this, x => x.IsAboutPage);}// 頁面選中態屬性(用于按鈕樣式綁定)private readonly ObservableAsPropertyHelper<bool> _isColorsPage;private readonly ObservableAsPropertyHelper<bool> _isAboutPage;public bool IsColorsPage => _isColorsPage.Value;public bool IsAboutPage => _isAboutPage.Value;}
}
4. 配置 IOC 容器(依賴注入)
為了實現 ViewModel 的解耦與復用,通過?Microsoft.Extensions.DependencyInjection
?配置 IOC 容器,在應用啟動時注冊 ViewModel 實例。
App.axaml.cs:應用啟動與 IOC 配置
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Data.Core.Plugins;
using Avalonia.Markup.Xaml;
using BasicRoutingExample.ViewModels;
using BasicRoutingExample.Views;
using Microsoft.Extensions.DependencyInjection;
using System;namespace BasicRoutingExample
{public partial class App : Application{// 應用初始化:加載 XAML 資源public override void Initialize(){AvaloniaXamlLoader.Load(this); }// 框架初始化完成:配置 IOC 并啟動主窗口public override void OnFrameworkInitializationCompleted(){// 移除默認數據驗證插件(避免不必要的驗證邏輯)BindingPlugins.DataValidators.RemoveAt(0);// 配置 IOC 服務Services = ConfigureServices();// 啟動桌面應用主窗口if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop){desktop.MainWindow = new MainWindow{DataContext = new MainWindowViewModel(), // 為主窗口綁定 ViewModel};} base.OnFrameworkInitializationCompleted();}// 靜態屬性:獲取當前應用實例public new static App Current => (App)Application.Current!;// IOC 服務容器public IServiceProvider? Services { get; private set; }// 配置 IOC 服務:注冊 ViewModel(瞬態模式,每次獲取新實例)private static ServiceProvider ConfigureServices(){var services = new ServiceCollection();services.AddTransient<ColorsViewModel>();services.AddTransient<AboutViewModel>();return services.BuildServiceProvider();}}
}
三、樣式美化:實現響應式按鈕與全局樣式
通過 Avalonia 的樣式系統,為按鈕添加 “默認態”“ hover 態”“選中態”,并統一全局控件樣式(如文本、邊框)。
1. 全局樣式配置(App.axaml)
<Application xmlns="https://github.com/avaloniaui"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"x:Class="BasicRoutingExample.App"xmlns:local="using:BasicRoutingExample"RequestedThemeVariant="Default"> <!-- 跟隨系統主題(淺色/深色) --><!-- View-ViewModel 匹配器:自動根據 ViewModel 加載 View --><Application.DataTemplates><local:ViewLocator/></Application.DataTemplates><!-- 資源定義:顏色、漸變等可復用資源 --><Application.Resources><!-- 主色調 --><SolidColorBrush x:Key="PrimaryBackground">#14172D</SolidColorBrush><SolidColorBrush x:Key="PrimaryForeground">#cfcfcf</SolidColorBrush><!-- 漸變背景 --><LinearGradientBrush x:Key="PrimaryGradient" StartPoint="0%,0%" EndPoint="100%,0%"><GradientStops><GradientStop Offset="0" Color="#111214"/><GradientStop Offset="1" Color="#151E3E"/></GradientStops></LinearGradientBrush><!-- 交互狀態顏色 --><SolidColorBrush x:Key="PrimaryHoverBackground">#333853</SolidColorBrush><SolidColorBrush x:Key="PrimaryHoverForeground">White</SolidColorBrush><SolidColorBrush x:Key="PrimaryActiveBackground">#334488</SolidColorBrush><SolidColorBrush x:Key="PrimaryActiveForeground">AliceBlue</SolidColorBrush></Application.Resources><!-- 全局控件樣式 --><Application.Styles><!-- 基礎主題(Fluent 風格) --><FluentTheme /> <!-- 文本框默認樣式 --><Style Selector="TextBlock"> <Setter Property="Foreground" Value="{StaticResource PrimaryForeground}"/><Setter Property="VerticalAlignment" Value="Center"/></Style><!-- 標題文本樣式(用于頁面標題) --><Style Selector="TextBlock.caption"> <Setter Property="FontSize" Value="28"/><Setter Property="HorizontalAlignment" Value="Center"/><Setter Property="VerticalAlignment" Value="Center"/></Style><!-- 菜單邊框樣式 --><Style Selector="Border.menu"> <Setter Property="Background" Value="{StaticResource PrimaryGradient}"/><Setter Property="Padding" Value="10"/></Style><!-- 內容區域邊框樣式 --><Style Selector="Border.client"> <Setter Property="Padding" Value="10"/><Setter Property="Background" Value="{StaticResource PrimaryBackground}"/></Style><!-- 按鈕基礎樣式 --><Style Selector="Button"> <Setter Property="HorizontalContentAlignment" Value="Center"/><Setter Property="Width" Value="150"/></Style><!-- 按鈕默認態 --><Style Selector="Button /template/ContentPresenter"> <Setter Property="Background" Value="Transparent"/><Setter Property="Foreground" Value="{StaticResource PrimaryForeground}"/><Setter Property="FontSize" Value="18"/> </Style><!-- 按鈕 hover 態(鼠標懸浮) --><Style Selector="Button:pointerover /template/ContentPresenter"><Setter Property="Background" Value="{StaticResource PrimaryHoverBackground}"/><Setter Property="Foreground" Value="{StaticResource PrimaryHoverForeground}"/></Style><!-- 按鈕選中態(當前頁面對應的按鈕) --><Style Selector="Button.active /template/ContentPresenter"><Setter Property="Background" Value="{StaticResource PrimaryActiveBackground}"/><Setter Property="Foreground" Value="{StaticResource PrimaryActiveForeground}"/></Style></Application.Styles>
</Application>
2. 導航按鈕實現(主窗口 XAML 片段)
通過?Classes.active
?綁定?IsColorsPage
/IsAboutPage
?屬性,實現 “選中態” 自動切換;通過?Command
?綁定導航命令,觸發頁面跳轉。
<!-- 顏色列表頁按鈕 -->
<Button Command="{Binding GotoColorsCommand}" Classes.active="{Binding IsColorsPage}"><StackPanel Orientation="Horizontal" Spacing="15"><Image Source="/Assets/images/colors.png" Width="32"/><TextBlock Text="顏色列表"/></StackPanel>
</Button><!-- 關于頁按鈕 -->
<Button Command="{Binding GotoAboutCommand}" Classes.active="{Binding IsAboutPage}"><StackPanel Orientation="Horizontal" Spacing="15"><Image Source="/Assets/images/aboutA.png" Width="32"/><TextBlock Text="關于應用"/></StackPanel>
</Button>
四、關鍵技巧與優化建議
1. 輕量轉換器?FuncValueConverter
?的優勢
Avalonia 提供的?FuncValueConverter
?無需創建單獨的轉換器類,可直接在 ViewModel 中定義為靜態屬性,減少代碼冗余。例如本文中 RGB 轉 CMYK 的轉換器,直接通過?x:Static
?引用即可使用:
<TextBlock Text="{Binding Color, Converter={x:Static vm:ColorsViewModel.ToCMYK}}"/>
2. 頁面切換的性能優化
- 避免重復實例化:在導航命令中添加判斷(如?
CurrentPage is not ColorsViewModel
),防止同一頁面被重復創建。 - 選擇合適的 IOC 生命周期:本文使用?
AddTransient
(瞬態模式,每次獲取新實例),若需保留頁面狀態,可改為?AddSingleton
(單例模式)或?AddScoped
(作用域模式)。
3. 響應式框架的選擇
- ReactiveUI:適合復雜交互場景,支持屬性監聽、響應式命令,但需要編寫較多模板代碼(如?
ObservableAsPropertyHelper
?相關邏輯)。 - CommunityToolkit.Mvvm:語法更簡潔,通過?
[ObservableProperty]
?[RelayCommand]
?等特性減少樣板代碼,適合快速開發。
五、總結
本文通過一個完整的示例,展示了 Avalonia 基礎導航的實現流程:從 ViewModel 設計(數據與命令)、View 布局(XAML 與數據綁定),到導航邏輯(_currentPage
?屬性管理)、樣式美化(響應式按鈕與全局樣式)。核心要點包括:
- 利用?
TransitioningContentControl
?與?_currentPage
?綁定實現頁面切換; - 通過 IOC 容器實現 ViewModel 的解耦與實例管理;
- 借助樣式系統與屬性監聽,實現交互狀態(如按鈕選中態)的自動同步。
掌握這些基礎后,可進一步擴展功能,例如添加頁面切換動畫、參數傳遞、導航歷史記錄等,構建更復雜的 Avalonia 多頁面應用。
運行效果圖