Avalonia 學(xué)習(xí)筆記06. Page Layout(頁面布局)
本節(jié)課程的目標(biāo)是根據(jù)一個(gè)預(yù)先設(shè)計(jì)好的 UI 模型,使用 Avalonia XAML 來構(gòu)建“設(shè)置”頁面的結(jié)構(gòu)。我們將重點(diǎn)放在如何使用 Grid 和 StackPanel 等布局控件來正確地放置元素,而將具體的樣式(如顏色、字體、邊框等)留到下一節(jié)課。這種將“結(jié)構(gòu)”和“樣式”分離的思路,是現(xiàn)代 UI 開發(fā)中的一個(gè)重要實(shí)踐。
6.1 ViewModels\MainViewModel.cs
我們首先對 MainViewModel 做一個(gè)小修改,以解決 XAML 設(shè)計(jì)器中的一個(gè)預(yù)覽問題。
using Avalonia.Svg.Skia; using AvaloniaApplication2.Data; using AvaloniaApplication2.Factories; using AvaloniaApplication2.Views; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using Microsoft.Extensions.DependencyInjection; namespace AvaloniaApplication2.ViewModels; public partial class MainViewModel : ViewModelBase { private PageFactory _pageFactory; [ObservableProperty] private bool _sideMenuExpanded = true; [ObservableProperty] [NotifyPropertyChangedFor(nameof(HomePageIsActive))] [NotifyPropertyChangedFor(nameof(ProcessPageIsActive))] [NotifyPropertyChangedFor(nameof(ActionsPageIsActive))] [NotifyPropertyChangedFor(nameof(MacrosPageIsActive))] [NotifyPropertyChangedFor(nameof(ReporterPageIsActive))] [NotifyPropertyChangedFor(nameof(HistoryPageIsActive))] [NotifyPropertyChangedFor(nameof(SettingsPageIsActive))] private PageViewModel _currentPage; public bool HomePageIsActive => CurrentPage.PageName == ApplicationPageNames.Home; public bool ProcessPageIsActive => CurrentPage.PageName == ApplicationPageNames.Process; public bool ActionsPageIsActive => CurrentPage.PageName == ApplicationPageNames.Actions; public bool MacrosPageIsActive => CurrentPage.PageName == ApplicationPageNames.Macros; public bool ReporterPageIsActive => CurrentPage.PageName == ApplicationPageNames.Reporter; public bool HistoryPageIsActive => CurrentPage.PageName == ApplicationPageNames.History; public bool SettingsPageIsActive => CurrentPage.PageName == ApplicationPageNames.Settings; /// <summary> /// 僅用于設(shè)計(jì)時(shí) (Design-Time only constructor)。 /// </summary> /// <remarks> /// 這個(gè)無參數(shù)的構(gòu)造函數(shù)是專門為 XAML 設(shè)計(jì)器準(zhǔn)備的。 /// 因?yàn)槲覀円肓艘蕾囎⑷?,原來的?gòu)造函數(shù)需要一個(gè) `PageFactory` 參數(shù), /// 這是在程序“運(yùn)行時(shí)”才由 DI 容器提供的。 /// XAML 設(shè)計(jì)器在“設(shè)計(jì)時(shí)”無法提供這個(gè)參數(shù),會導(dǎo)致預(yù)覽失敗。 /// 通過添加這個(gè)無參數(shù)構(gòu)造函數(shù),并為 `CurrentPage` 設(shè)置一個(gè)默認(rèn)頁面(這里是 SettingsPageViewModel), /// 設(shè)計(jì)器就能夠成功實(shí)例化 MainViewModel,從而正常顯示 MainView 的預(yù)覽界面。 /// </remarks> public MainViewModel() { CurrentPage = new SettingsPageViewModel(); } public MainViewModel(PageFactory pageFactory) { _pageFactory = pageFactory; GoToHome(); } [RelayCommand] private void SideMenuResize() { SideMenuExpanded = !SideMenuExpanded; } [RelayCommand] private void GoToHome() { CurrentPage = _pageFactory.GetPageViewModel(ApplicationPageNames.Home); } [RelayCommand] private void GoToProcess() { CurrentPage = _pageFactory.GetPageViewModel(ApplicationPageNames.Process); } [RelayCommand] private void GoToMacros() { CurrentPage = _pageFactory.GetPageViewModel(ApplicationPageNames.Macros); } [RelayCommand] private void GoToActions() { CurrentPage = _pageFactory.GetPageViewModel(ApplicationPageNames.Actions); } [RelayCommand] private void GoToReporter() { CurrentPage = _pageFactory.GetPageViewModel(ApplicationPageNames.Reporter); } [RelayCommand] private void GoToHistory() { CurrentPage = _pageFactory.GetPageViewModel(ApplicationPageNames.History); } [RelayCommand] private void GoToSettings() { CurrentPage = _pageFactory.GetPageViewModel(ApplicationPageNames.Settings); } }
6.2 ViewModels\SettingsPageViewModel.cs
這是為“設(shè)置”頁面創(chuàng)建的新的 ViewModel。我們在這里添加一些臨時(shí)的示例數(shù)據(jù),以便在 UI 上看到列表的顯示效果。
using System.Collections.Generic; using AvaloniaApplication2.Data; using CommunityToolkit.Mvvm.ComponentModel; namespace AvaloniaApplication2.ViewModels; public partial class SettingsPageViewModel : PageViewModel { // 使用 [ObservableProperty] 特性,CommunityToolkit.Mvvm 會自動為私有字段 `_locationPaths` // 生成一個(gè)名為 `LocationPaths` 的公共屬性。 // 這個(gè)屬性會自動實(shí)現(xiàn) INotifyPropertyChanged 接口,當(dāng)它的值改變時(shí),會通知 UI 更新。 [ObservableProperty] private List<string> _locationPaths; public SettingsPageViewModel() { PageName = ApplicationPageNames.Settings; // TEMP: Remove // 在構(gòu)造函數(shù)中,我們?yōu)?LocationPaths 初始化了一些臨時(shí)的假數(shù)據(jù)。 // 這使得我們在開發(fā) UI 界面時(shí),即使沒有后端邏輯,也能看到列表的實(shí)際顯示效果。 // 這里使用了 C# 12 的集合表達(dá)式 `[...]` 和逐字字符串 `@""`,使代碼更簡潔。 LocationPaths = [ @"C:\Users\Luke\Downloads\TestActions", @"C:\Users\Luke\Documents\BatchProcess", @"X:\Shared\BatchProcess\Templates" ]; } }
6.3 Views\SettingsPageView.axaml
這是本節(jié)課的核心,即“設(shè)置”頁面的 XAML 結(jié)構(gòu)代碼。我們一步步將設(shè)計(jì)圖分解為 XAML 控件。
<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="clr-namespace:AvaloniaApplication2.ViewModels" mc:Ignorable="d" d:DesignWidth="1100" d:DesignHeight="900" Background="{DynamicResource PrimaryBackground}" Foreground="{DynamicResource PrimaryForeground}" x:DataType="vm:SettingsPageViewModel" x:Class="AvaloniaApplication2.Views.SettingsPageView"> <!-- 為設(shè)計(jì)器提供數(shù)據(jù)上下文(DataContext)。 這行代碼告訴 XAML 設(shè)計(jì)器在預(yù)覽時(shí)使用 `SettingsPageViewModel` 的一個(gè)實(shí)例作為數(shù)據(jù)源。 這使得在設(shè)計(jì)器中可以看到數(shù)據(jù)綁定(如 ItemsSource="{Binding LocationPaths}")的效果。 它只在設(shè)計(jì)時(shí)生效,不影響程序?qū)嶋H運(yùn)行。 --> <Design.DataContext><vm:SettingsPageViewModel></vm:SettingsPageViewModel></Design.DataContext> <!-- 頁面根布局:一個(gè)2行2列的 Grid。 - ColumnDefinitions="*, *": 定義兩個(gè)寬度相等的列,它們會平分所有可用寬度。 - RowDefinitions="Auto, *": 定義兩行。第一行(頭部)的高度由其內(nèi)容決定(Auto),第二行(內(nèi)容區(qū))占據(jù)所有剩余的高度(*)。 這是構(gòu)建經(jīng)典“頭+體”布局的常用方式。 --> <Grid ColumnDefinitions="*, *" RowDefinitions="Auto, *"> <!-- Header: 頭部區(qū)域 --> <!-- Grid.ColumnSpan="2" 讓這個(gè)頭部的 Grid 橫跨兩列 --> <Grid Name="HeaderGrid" Grid.ColumnSpan="2"> <!-- Grid 是一個(gè)很好的堆疊控件。這里我們將 Image 和 StackPanel 放在同一個(gè)單元格中, 它們會重疊在一起,Image 在下,StackPanel 在上。 - Image 的 Stretch="UniformToFill" 屬性確保圖片在保持自身比例的同時(shí),填滿整個(gè)容器區(qū)域,超出部分會被裁剪。 --> <Image Source="{SvgImage /Assets/Images/background-settings.svg}" Height="160" Stretch="UniformToFill"></Image> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <Label HorizontalAlignment="Center" Content="Settings"></Label> <Label HorizontalAlignment="Center" Content="Version 3.0.0.2 Beta"></Label> <Label HorizontalAlignment="Center" Content="Compiled Jul 07 2025"></Label> </StackPanel> </Grid> <!-- Left side content: 左側(cè)內(nèi)容區(qū) --> <!-- - Grid.Column="0" Grid.Row="1" 將這個(gè) StackPanel 放置在主 Grid 的第一列、第二行。 - Spacing="10" 為 StackPanel 內(nèi)的直接子元素(如此處的 General 和 Location 兩個(gè)區(qū)域)之間添加 10 個(gè)單位的垂直間距。 - Margin="15" 在 StackPanel 的四周添加 15 個(gè)單位的外邊距,起到內(nèi)邊距的效果,讓內(nèi)容不至于貼邊。 --> <StackPanel Grid.Column="0" Grid.Row="1" Spacing="10" Margin="15"> <!-- General: “常規(guī)”設(shè)置區(qū)域 --> <StackPanel> <Label Content="General"></Label> <!-- 使用一個(gè)嵌套的 Grid 來對齊左側(cè)的描述文本和右側(cè)的控件。 - ColumnDefinitions="*, Auto": 左列占據(jù)所有剩余空間,右列寬度由其內(nèi)容(按鈕、復(fù)選框)決定。 --> <Grid ColumnDefinitions="*, Auto" RowDefinitions="Auto, Auto, Auto"> <!-- Release license --> <!-- TextBlock 用于顯示長文本,因?yàn)樗С?TextWrapping="Wrap" 自動換行。Label 不支持。--> <TextBlock TextWrapping="Wrap" Text="Remove license of BatchProcess from this machine and release the license back to the server ready to be transferred to another machine."></TextBlock> <Button Grid.Row="0" Grid.Column="1" HorizontalAlignment="Stretch"> <StackPanel Orientation="Horizontal"> <!--  是一個(gè)圖標(biāo)字體的 Unicode 編碼,用于顯示圖標(biāo) --> <Label Classes="icon" Content=""></Label> <Label Classes="akko" Content="Release License"></Label> </StackPanel> </Button> <!-- Skip Files --> <TextBlock Grid.Row="1" Grid.Column="0" TextWrapping="Wrap" Text="Skip files if only Open, Save (Optional) and Close are Valid actions."></TextBlock> <CheckBox Grid.Row="1" Grid.Column="1"></CheckBox> <!-- Duplicate Entries --> <TextBlock Grid.Row="2" Grid.Column="0" TextWrapping="Wrap" Text="Allow duplicate entries of the same file in project list"></TextBlock> <CheckBox Grid.Row="2" Grid.Column="1"></CheckBox> </Grid> </StackPanel> <!-- Location: “位置”設(shè)置區(qū)域 --> <StackPanel> <Label Content="Location"></Label> <Grid ColumnDefinitions="*, Auto"> <StackPanel> <TextBlock TextWrapping="Wrap" Text="Add or remove the locations to search for Reporter Templates, Macros, Actions and other custom files or templates."></TextBlock> <TextBlock TextWrapping="Wrap" Text="All sub-directories will be searched automatically"></TextBlock> </StackPanel> <Button Grid.Column="1" HorizontalAlignment="Stretch"> <StackPanel Orientation="Horizontal"> <Label Classes="akko" Content="+ Folder"></Label> </StackPanel> </Button> </Grid> <!-- 使用 ListBox 來顯示文件夾路徑列表。 - ItemsSource="{Binding LocationPaths}" 是核心的數(shù)據(jù)綁定語法,它將此列表的數(shù)據(jù)源綁定到 ViewModel 中的 `LocationPaths` 屬性。 - 選擇 ListBox 而不是更基礎(chǔ)的 ItemsControl,是因?yàn)?ListBox 自帶了選中、懸停等交互效果和基本樣式,方便后續(xù)功能開發(fā)。 --> <ListBox ItemsSource="{Binding LocationPaths}"></ListBox> </StackPanel> </StackPanel> <!-- Right Side Content: 右側(cè)內(nèi)容區(qū) --> <StackPanel Grid.Column="1" Grid.Row="1" Spacing="10" Margin="15"> <!-- SolidWorks Host --> <StackPanel> <Label Content="SolidWorks Host"></Label> <TextBlock TextWrapping="Wrap"> BatchProcess can work locally on the current machine, or on any machine accessible over the network or even internet.<LineBreak /><LineBreak /> Enter the machines IP address, network name or localhost for this machine. </TextBlock> <ComboBox></ComboBox> <Label Content="Connection established"></Label> </StackPanel> <!-- PDM Enterprise --> <StackPanel Spacing="15"> <Label Content="PDM Enterprise"></Label> <TextBlock TextWrapping="Wrap" Text="If you are using PDM Enterprise enter the credentials below and test login. BatchProcess can then automatically handle checking in and out files from PDM Enterprise."></TextBlock> <!-- 這里使用三列等寬的 Grid,是為了讓三個(gè)輸入框(ComboBox, TextBox, TextBox)平分橫向空間。 如果使用水平 StackPanel,它們只會各自占據(jù)所需寬度,無法實(shí)現(xiàn)均分拉伸的效果。 --> <Grid ColumnDefinitions="*, *, *"> <ComboBox HorizontalAlignment="Stretch"></ComboBox> <TextBox Grid.Column="1"></TextBox> <TextBox Grid.Column="2"></TextBox> </Grid> <StackPanel Orientation="Horizontal"> <Button Grid.Column="1" HorizontalAlignment="Stretch"> <StackPanel Orientation="Horizontal"> <Label Classes="icon" Content=""></Label> <Label Classes="akko" Content="Login"></Label> </StackPanel> </Button> <Button Grid.Column="1" HorizontalAlignment="Stretch"> <StackPanel Orientation="Horizontal"> <Label Classes="icon" Content=""></Label> <Label Classes="akko" Content="Refresh Vault"></Label> </StackPanel> </Button> </StackPanel> <Label Content="Connection Established"></Label> </StackPanel> <!-- Setting Cache --> <StackPanel Spacing="15"> <Label Content="Setting Cache"></Label> <TextBlock TextWrapping="Wrap"> Various settings are stored locally including Processes, Actions, Macros, Reports and History. <LineBreak /><LineBreak /> If you are experiencing issues you can try clearing the cache (this won't remove the license). </TextBlock> <StackPanel Orientation="Horizontal"> <Button Grid.Column="1" HorizontalAlignment="Stretch"> <StackPanel Orientation="Horizontal"> <Label Classes="icon" Content=""></Label> <Label Classes="akko" Content="Clear Cache"></Label> </StackPanel> </Button> <Button Grid.Column="1" HorizontalAlignment="Stretch"> <StackPanel Orientation="Horizontal"> <Label Classes="icon" Content=""></Label> <Label Classes="akko" Content="Export Cache"></Label> </StackPanel> </Button> <Button Grid.Column="1" HorizontalAlignment="Stretch"> <StackPanel Orientation="Horizontal"> <Label Classes="icon" Content=""></Label> <Label Classes="akko" Content="Import Cache"></Label> </StackPanel> </Button> </StackPanel> </StackPanel> </StackPanel> </Grid> </UserControl>

浙公網(wǎng)安備 33010602011771號