学习目标

  • 理解 XAML 与 C# 对象之间的映射关系,能读懂并手写基本界面
  • 掌握 Grid / StackPanel / DockPanel / UniformGrid / WrapPanel 五大布局面板,能按场景选型
  • 掌握 Grid 的行列定义与 SharedSizeGroup 共享尺寸机制
  • 摆脱 WinForm”拖控件 + 绝对定位”思维,建立 WPF”布局协商”思维
  • 能用 Visual Studio 2022 独立创建并运行一个 WPF .NET 8 项目

前置知识

无(本资料是 WPF 模块的第一篇)。

核心概念讲解

1. XAML 是什么

XAML 是 C# 对象的 XML 序列化形式。一行 XAML 对应一段 C# 对象初始化代码:

<Button Content="启动设备" Width="90" Height="32"/>

等价于:

var btn = new Button { Content = "启动设备", Width = 90, Height = 32 };

三条核心语法规则:

  • 标签名 = 类名(Button、Grid 都是 System.Windows.Controls 里的类)
  • 特性(Attribute)= 属性赋值,但只支持基本类型;复杂属性用”属性元素”语法:<Grid.RowDefinitions>...</Grid.RowDefinitions>
  • 花括号语法叫”标记扩展”,如 {Binding Name}、{StaticResource brush},本质是让编译器生成对象

2. WPF 布局思维:两阶段协商

WPF 布局是一次递归过程:父容器先 Measure(询问每个子元素想要多大),再 Arrange(把实际区域分配给子元素)。每个面板实现自己的”问询策略”,例如:

  • StackPanel:水平排列时无视子元素宽度,只要高度
  • Grid:按行列权重瓜分空间
  • WrapPanel:放不下就换行/换列

因此控件没有 WinForm 那种绝对 Left/Top 概念(Canvas 除外),控件的位置由所在面板决定。

3. 五大布局面板

Grid:表格布局,工业界面主力。 用行列切分区域,支持按比例瓜分:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>   <!-- 自适应内容高度 -->
        <RowDefinition Height="*"/>       <!-- 占据剩余空间 -->
        <RowDefinition Height="30"/>      <!-- 固定 30 像素 -->
    </Grid.RowDefinitions>
    <Button Grid.Row="0" Content="工具栏"/>
    <Border Grid.Row="1" Background="LightGray"/>
    <StatusBar Grid.Row="2"/>
</Grid>

Grid.Row / Grid.Column 叫”附加属性”,本质是 Grid 类把行列号存储到子元素身上,Grid 自己读取并排版。

StackPanel:单向堆叠,最简单。

<StackPanel Orientation="Vertical">
    <TextBlock Text="设备状态:运行"/>
    <TextBlock Text="当前工位:3"/>
    <Button Content="停止"/>
</StackPanel>

DockPanel:停靠布局,适合”工具栏+主区+状态栏”骨架。

<DockPanel>
    <Menu DockPanel.Dock="Top" Height="25"/>     <!-- 顶部菜单 -->
    <Border DockPanel.Dock="Left" Width="200"/>  <!-- 左侧设备列表 -->
    <StatusBar DockPanel.Dock="Bottom"/>        <!-- 底部状态栏 -->
    <Border Background="White"/>                <!-- 未设置停靠:填满剩余 -->
</DockPanel>

注意:最后一个未指定 Dock 的子元素自动填满剩余空间,无需写 Dock=“Fill”。

UniformGrid:等分网格,按钮矩阵专用。

<UniformGrid Rows="2" Columns="2">
    <Button Content="工位1"/>
    <Button Content="工位2"/>
    <Button Content="复位"/>
    <Button Content="急停"/>
</UniformGrid>

WrapPanel:流式换行,工具箱式排列。

<WrapPanel>
    <Button Content="轴1" Width="70"/>
    <Button Content="轴2" Width="70"/>
    <Button Content="轴3" Width="70"/>
</WrapPanel>

4. Grid 的行列与 SharedSizeGroup

SharedSizeGroup 让多个 Grid(甚至不同 Grid 之间)的列保持同宽,典型用途:让左右两列”标签+输入框”完全对齐。前提是外层容器声明 Grid.IsSharedSizeScope="True":

<StackPanel Grid.IsSharedSizeScope="True">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="labelCol"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Text="波特率:"/>
        <TextBox Grid.Column="1"/>
    </Grid>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="labelCol"/>  <!-- 与上一行的 labelCol 同宽 -->
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Text="数据位:"/>
        <TextBox Grid.Column="1"/>
    </Grid>
</StackPanel>

5. Margin 与对齐

  • Margin 顺序为”左、上、右、_bottom”,四值写法如 Margin="10,5,10,5"
  • HorizontalAlignment:Left / Center / Right / Stretch(水平位置)
  • VerticalAlignment:Top / Center / Bottom / Stretch(垂直位置)
  • 控件默认 HorizontalAlignment 为 Stretch,会尽力占满可用宽度;改成 Left 才会收缩到内容宽度
  • 宽高未设置时,对齐方式决定控件的尺寸行为;同时设置 Width 和 Stretch,Width 生效

6. WinForm vs WPF 思维差异(写给后端工程师)

维度 WinForm 思维 WPF 思维
界面描述 拖控件进设计器,自动生成 InitializeComponent 手写 XAML,或用设计器辅助生成
定位方式 Location 绝对坐标(Left/Top) 由布局面板决定位置
界面与代码耦合 控件属性散落在代码里 属性尽量写在 XAML,代码只写逻辑(进阶后用绑定代替直接操作控件)
缩放适配 控件位置固定,改分辨率需手动处理 布局随容器自动缩放
换肤/外观 每个控件设置属性,难以统一修改 通过样式与模板统一管理
类比 像”存储过程式 UI” 像”声明式前端页面”(类似 HTML+CSS,逻辑分离开来)

一句话:WinForm 把界面当”对象集合”操作,WPF 把界面当”数据的一种视图”。上位机需要频繁换界面风格、动态增减监控点,声明式布局是刚性需求。

7. WPF 项目结构

  • App.xaml + App.xaml.cs:应用程序入口,StartupUri 指向首个窗口
  • App.xaml 的 Resources:全局资源字典,样式统一放这里
  • MainWindow.xaml + .xaml.cs:窗口文件
  • Window / Page / UserControl 的区别:
    • Window:独立窗口(对话框、主窗口)
    • Page:导航容器中的页面(像浏览器页),常与 Frame 配合
    • UserControl:可复用的界面片段,是封装自定义显示控件的主要手段

代码实战

用 Visual Studio 2022(17.8+)创建项目:

  1. 新建项目 → 搜索”WPF 应用程序”(模板名:WPF Application,C#)
  2. 框架选择 .NET 8.0
  3. 项目命名后创建,得到一个含 App.xaml 与 MainWindow.xaml 的可运行项目

下面实现一个典型的上位机界面骨架:顶部工具栏、左侧设备列表、主区域显示区、底部状态栏。

App.xaml(默认即可):

<Application x:Class="WpfLayoutDemo.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="MainWindow.xaml">
    <Application.Resources/>
</Application>

MainWindow.xaml:

<Window x:Class="WpfLayoutDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="设备监控台" Height="520" Width="820"
        WindowStartupLocation="CenterScreen">
    <DockPanel>
        <!-- 顶部工具栏:菜单 + 常用按钮 -->
        <StackPanel DockPanel.Dock="Top" Orientation="Horizontal" Margin="4">
            <Button Content="连接" Width="70" Margin="0,0,6,0"/>
            <Button Content="断开" Width="70" Margin="0,0,6,0"/>
            <Button Content="重连" Width="70"/>
        </StackPanel>

        <!-- 底部状态栏 -->
        <StatusBar DockPanel.Dock="Bottom">
            <StatusBarItem>
                <TextBlock x:Name="StatusText" Text="就绪"/>
            </StatusBarItem>
        </StatusBar>

        <!-- 左侧设备列表:固定宽度 200 -->
        <Border DockPanel.Dock="Left" Width="200" BorderBrush="Gray" BorderThickness="0,0,1,0">
            <StackPanel Margin="4">
                <TextBlock Text="设备列表" FontWeight="Bold"/>
                <ListBox Margin="0,4,0,0">
                    <ListBoxItem Content="1 号温控仪"/>
                    <ListBoxItem Content="2 号温控仪"/>
                    <ListBoxItem Content="PLC 主站"/>
                </ListBox>
            </StackPanel>
        </Border>

        <!-- 主区域:两行 Grid,上面数值区,下面参数区 -->
        <Grid Margin="4">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>

            <!-- 数值显示区:UniformGrid 等分四格 -->
            <UniformGrid Grid.Row="0" Rows="1" Columns="4">
                <Border BorderBrush="LightGray" BorderThickness="1" Margin="2">
                    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                        <TextBlock Text="当前温度" HorizontalAlignment="Center"/>
                        <TextBlock x:Name="TempText" Text="25.6 ℃" FontSize="20" FontWeight="Bold"
                                   HorizontalAlignment="Center"/>
                    </StackPanel>
                </Border>
                <Border BorderBrush="LightGray" BorderThickness="1" Margin="2">
                    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                        <TextBlock Text="目标温度" HorizontalAlignment="Center"/>
                        <TextBlock Text="80.0 ℃" FontSize="20" FontWeight="Bold"
                                   HorizontalAlignment="Center"/>
                    </StackPanel>
                </Border>
                <Border BorderBrush="LightGray" BorderThickness="1" Margin="2">
                    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                        <TextBlock Text="运行状态" HorizontalAlignment="Center"/>
                        <TextBlock Text="运行中" FontSize="20" FontWeight="Bold" Foreground="Green"
                                   HorizontalAlignment="Center"/>
                    </StackPanel>
                </Border>
                <Border BorderBrush="LightGray" BorderThickness="1" Margin="2">
                    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                        <TextBlock Text="今日产量" HorizontalAlignment="Center"/>
                        <TextBlock Text="1200" FontSize="20" FontWeight="Bold"
                                   HorizontalAlignment="Center"/>
                    </StackPanel>
                </Border>
            </UniformGrid>

            <!-- 参数区:Grid + SharedSizeGroup 对齐标签 -->
            <StackPanel Grid.IsSharedSizeScope="True" Grid.Row="1" Margin="4">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition SharedSizeGroup="lbl"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition SharedSizeGroup="lbl"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <TextBlock Grid.Row="0" Grid.Column="0" Text="串口号:"/>
                    <TextBox Grid.Row="0" Grid.Column="1" Text="COM3" Margin="0,0,8,8"/>
                    <TextBlock Grid.Row="0" Grid.Column="2" Text="波特率:"/>
                    <TextBox Grid.Row="0" Grid.Column="3" Text="115200" Margin="0,0,0,8"/>
                    <TextBlock Grid.Row="1" Grid.Column="0" Text="采样周期:"/>
                    <TextBox Grid.Row="1" Grid.Column="1" Text="500" Margin="0,0,8,8"/>
                    <TextBlock Grid.Row="1" Grid.Column="2" Text="报警上限:"/>
                    <TextBox Grid.Row="1" Grid.Column="3" Text="90" Margin="0,0,0,8"/>
                </Grid>

                <!-- 底部按钮组:WrapPanel -->
                <WrapPanel>
                    <Button Content="保存参数" Width="80" Margin="0,0,6,0"/>
                    <Button Content="恢复默认" Width="80" Margin="0,0,6,0"/>
                    <Button Content="导出配置" Width="80"/>
                </WrapPanel>
            </StackPanel>
        </Grid>
    </DockPanel>
</Window>

MainWindow.xaml.cs(仅补一个模拟温度刷新,重点在布局):

using System.Windows;

namespace WpfLayoutDemo;

public partial class MainWindow : Window
{
    private readonly Random _random = new();   // 模拟数据源

    public MainWindow()
    {
        InitializeComponent();
        var timer = new System.Windows.Threading.DispatcherTimer  // UI 线程定时器
        {
            Interval = TimeSpan.FromSeconds(1)
        };
        timer.Tick += (s, e) =>
        {
            double t = 24 + _random.NextDouble() * 4;   // 生成 24~28 的随机温度
            TempText.Text = $"{t:F1} ℃";                // 直接刷新界面文本
        };
        timer.Start();
    }
}

目标框架:net8.0-windows;NuGet 依赖:无(纯 WPF 内置控件即可运行)。

动手练习

  1. 基础:把左侧设备列表改为 180 宽并加一个”扫描设备”按钮,观察 DockPanel 剩余空间变化
  2. 进阶:将主区域 UniformGrid 从 1x4 改为 2x2,观察 UniformGrid 自动换行行为与 Grid 混合布局的差异
  3. 挑战:新增一个”报警记录”区域(右侧停靠,宽 240),其中用 WrapPanel 摆放 6 个 60x40 的报警占位按钮,体会流式换行

常见坑与注意事项

  • 忘写 Grid.Row / Grid.Column 时默认在 Row=0、Column=0,多个控件会叠在第 0 格
  • Height 写 * 是”按比例瓜分剩余空间”,Auto 是”包住内容”,不要混淆;3 行 * 表示三行平分
  • SharedSizeGroup 必须配合 Grid.IsSharedSizeScope="True" 使用,且分组名区分大小写
  • Margin 是”左,上,右,下”顺序而非”上,右,下,左”(后者是 CSS 的习惯),二值写法 Margin="10,5" 表示”左右 10、上下 5”
  • StackPanel 垂直方向不给子元素高度限制,里面放 Grid/ScrollViewer 的 * 尺寸会失效,界面会被”撑开”
  • HorizontalAlignment 默认是 Stretch,设置了 Width 后以 Width 为准;调试布局时给 Border 加背景色是定位问题的最快手段
  • XAML 区分大小写,grid.row 无效必须写 Grid.Row
  • 设计器拖拽生成的界面往往嵌套冗余,实际项目以手写 XAML 为主,设计器只做预览

自查清单