教程:使用 C# 创建简单 WPF 应用

通过完成本教程,你将熟悉在使用 Visual Studio 开发应用程序时可使用的许多工具、对话框和设计器。 你将创建“Hello, World”应用程序、设计 UI、添加代码并调试错误。在此期间,你将了解如何使用集成开发环境 (IDE)。

先决条件

  • 如果尚未安装 Visual Studio,请转到 Visual Studio 下载页免费安装。
  • 确保安装了 .NET 桌面开发工作负载。 可以在 Visual Studio 安装程序中验证此配置。
  • 在本教程中,可以使用 .NET Framework 或 .NET Core。 .NET Core 是较新的、更新式的框架。 .NET Core 需要 Visual Studio 2019 16.3 或更高版本。

什么是 WPF?

Windows Presentation Foundation (WPF) 是一个可创建桌面客户端应用程序的 UI(用户界面)框架。 WPF 开发平台支持广泛的应用开发功能,包括应用模型、资源、控件、图形、布局、数据绑定、文档和安全性。

WPF 是 .NET 的一部分,因此,如果你曾经使用 ASP.NET 或 Windows 窗体通过 .NET 构建应用程序,应该会熟悉此编程体验。 WPF 使用 Extensible Application Markup Language (XAML) 为应用程序编程提供声明性模型。 有关详细信息,请参阅 WPF .NET 概述

配置 IDE

启动 Visual Studio 时,“启动”窗口首先打开。 选择“继续但无需代码”打开开发环境。 将看到工具窗口、菜单和工具栏,以及主窗口空间。 工具窗口位于应用程序窗口的左右两侧。 搜索框、菜单栏和标准工具栏位于顶部。 加载解决方案或项目时,编辑器和设计器显示在应用程序窗口中间。 开发应用程序时,大部分时间都在此中心区域。

创建项目

在 Visual Studio 中创建应用程序时,应首先创建项目和解决方案。 在本示例中,你将创建一个 Windows Presentation Foundation (WPF) 项目。

  1. 打开 Visual Studio。

  2. 在“开始”窗口上,选择“创建新项目”。

    View the 'Create a new project' window

  3. 在“创建新项目”屏幕上,搜索“WPF”,选择“WPF 应用程序”,然后选择“下一步” 。

    Screenshot of the 'Create a new project' dialog with 'WPF' entered in the search box, and the 'WPF Application' project template highlighted.

  4. 在下一个屏幕中,为项目指定名称“HelloWPFApp”,然后选择“下一步”。

    Screenshot of the 'Configure your new project' dialog in Visual Studio with 'HelloWPFApp' entered in the Project name field.

  5. 在“附加信息”窗口中,应已为目标框架选择“.NET Core 3.1” 。 如果未选择,则请选择“.NET Core 3.1”。 然后,选择“创建”。

    Screenshot that shows the Additional information window in Visual Studio with .NET Core 3.1 selected as the target framework for the new project.

Visual Studio 将创建 HelloWPFApp 项目和解决方案,“解决方案资源管理器”将显示各种文件。 “WPF 设计器”在拆分视图中显示 MainWindow.xaml 的设计视图和 XAML 视图。 您可以滑动拆分器,以显示任一视图的更多或更少部分。 您可以选择只查看可视化视图或 XAML 视图。

WPF project and solution in the IDE

注意

若要详细了解 XAML (eXtensible Application Markup Language),请参阅 WPF 的 XAML 概述页。

你可以在创建项目后进行自定义。 若要执行此操作,请从“视图”菜单中选择“属性窗口”或按 F4 。 然后可显示和更改应用程序中的项目项、控件和其他项的选项。

Properties window

  1. 打开 Visual Studio。

  2. 在“开始”窗口上,选择“创建新项目” 。

    Screenshot of the start window in Visual Studio 2022 with the 'Create a new project' option highlighted.

  3. 在“创建新项目”屏幕上,搜索“WPF”,选择“WPF 应用程序”,然后选择“下一步” 。

    Screenshot of the 'Create a new project' dialog with 'WPF' entered in the search box, and the 'WPF Application' project template highlighted.

  4. 在下一个屏幕中,为项目指定名称“HelloWPFApp”,然后选择“下一步”。

    Screenshot that shows the 'Configure your new project' dialog in Visual Studio with 'HelloWPFApp' entered in the Project name field.

  5. 在“其他信息”窗口中,验证是否为目标框架选择了“.NET 8.0”。 然后,选择“创建” 。

    Screenshot that shows the Additional information window in Visual Studio with .NET 8.0 selected as the target framework for the new project.

Visual Studio 将创建 HelloWPFApp 项目和解决方案,“解决方案资源管理器”将显示各种文件。 “WPF 设计器”在拆分视图中显示 MainWindow.xaml 的设计视图和 XAML 视图。 您可以滑动拆分器,以显示任一视图的更多或更少部分。 您可以选择只查看可视化视图或 XAML 视图。

Screenshot of the HelloWPFApp project and solution in Solution Explorer, and the XAML and designer views of 'MainWindow.xaml' open in the WPF Designer.

注意

若要详细了解 XAML (eXtensible Application Markup Language),请参阅 WPF 的 XAML 概述页。

你可以在创建项目后进行自定义。 若要执行此操作,请从“视图”菜单中选择“属性窗口”或按 F4 。 然后可显示和更改应用程序中的项目项、控件和其他项的选项。

Screenshot of the Properties window showing the Misc section of the Solution Properties for the HelloWPFApp project.

设计用户界面 (UI)

如果设计器未打开,请选择“MainWindow.xaml”,然后按 Shift+F7 打开设计器。

我们会将三种类型的控件添加到此应用程序:一个 TextBlock 控件、两个 RadioButton 控件和一个 Button 控件。

添加 TextBlock 控件

  1. 按“Ctrl+Q”激活搜索框,然后键入“工具箱” 。 从结果列表中选择“查看”>“工具箱”。

  2. 在“工具箱”中,展开“公共 WPF 控件”节点以查看 TextBlock 控件。

    Toolbox with the TextBlock control highlighted

  3. 通过选择“TextBlock”项并将其拖到设计图面的窗口中,将 TextBlock 控件添加到设计图面中。 把控件居中到窗口的顶部附近。 在 Visual Studio 2019 和更高版本中,可以使用红色参考线来使控件居中。

    你的窗口应与下图类似:

    TextBlock control on the MainWindow form

    XAML 标记应如下面的示例所示:

    <Grid>
        <TextBlock HorizontalAlignment="Left" Margin="387,60,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
    </Grid>
    
  1. 按“Ctrl+Q”激活搜索框,然后键入“工具箱” 。 从结果列表中选择“查看”>“工具箱”。

  2. 在“工具箱”中,展开“公共 WPF 控件”节点以查看 TextBlock 控件。

    Screenshot of the Toolbox window with the TextBlock control selected in the list of Common WPF Controls.

  3. 通过选择“TextBlock”项并将其拖到设计图面的窗口中,将 TextBlock 控件添加到设计图面中。 把控件居中到窗口的顶部附近。 可以使用参考线将控件居中。

    你的窗口应类似于下图:

    Screenshot of the TextBlock control on the design surface. Guidelines are shown for positioning and resizing the control.

    XAML 标记应如下面的示例所示:

    <Grid>
        <TextBlock HorizontalAlignment="Left" Margin="387,60,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top"/>
    </Grid>
    

自定义文本块中的文本

  1. 在 XAML 视图中,找到 TextBlock 的标记并将 Text 属性从 TextBox 更改为 Select a message option and then choose the Display button.

    XAML 标记应如下面的示例所示:

    <Grid>
        <TextBlock HorizontalAlignment="Left" Margin="387,60,0,0" TextWrapping="Wrap" Text="Select a message option and then choose the Display button." VerticalAlignment="Top"/>
    </Grid>
    
  2. 如果愿意,再次使 TextBlock 居中,然后通过按 Ctrl+S 或使用“文件” 菜单项保存更改。

接下来,向窗体添加两个 RadioButton 控件。

添加单选按钮

  1. 在“工具箱”中,查找“RadioButton”控件。

    Toolbox window with RadioButton control selected

  2. 通过选择“RadioButton”项并将其拖到设计图面的窗口中,将两个 RadioButton 控件添加到设计图面中。 移动按钮(通过选择它们并使用箭头键),以便按钮并排显示在 TextBlock 控件下。 使用红色参考线来对齐控件。

    你的窗口应如下所示:

    MainWindow form with TextBlock and two radio buttons

  3. 在左侧 RadioButton 控件的 “属性” 窗口中,将 “名称” 属性(位于 “属性” 窗口顶部)更改为 HelloButton

    RadioButton properties window

  4. 在右侧 RadioButton 控件的“属性”窗口中,将“名称”属性更改为 GoodbyeButton,然后保存更改。

接下来,为每个 RadioButton 控件添加显示文本。 以下程序将更新 RadioButton 控件的 “内容” 属性。

  1. 在“工具箱”中,查找“RadioButton”控件。

    Screenshot of the Toolbox window with the RadioButton control selected in the list of Common WPF Controls.

  2. 通过选择“RadioButton”项并将其拖到设计图面的窗口中,将两个 RadioButton 控件添加到设计图面中。 移动按钮(通过选择它们并使用箭头键),以便按钮并排显示在 TextBlock 控件下。 可以使用参考线来对齐控件。

    你的窗口应如下所示:

    Screenshot of the Design window for Greetings.xaml, showing a TextBlock control and two RadioButton controls positioned on the design surface.

  3. 在左侧 RadioButton 控件的 “属性” 窗口中,将 “名称” 属性(位于 “属性” 窗口顶部)更改为 HelloButton

    Screenshot of the Properties window for a RadioButton control. The value of the Name property has been changed to HelloButton.

  4. 在右侧 RadioButton 控件的“属性”窗口中,将“名称”属性更改为 GoodbyeButton,然后保存更改。

接下来,为每个 RadioButton 控件添加显示文本。 以下程序将更新 RadioButton 控件的 “内容” 属性。

添加每个单选按钮的显示文本

  1. 在 XAML 中将两个单选按钮 HelloButtonGoodbyeButton 的“内容”属性更新为 "Hello""Goodbye"。 XAML 标记现在应类似于以下示例:

    <Grid>
         <TextBlock HorizontalAlignment="Left" Margin="252,47,0,0" TextWrapping="Wrap" Text="Select a message option and then choose the Display button." VerticalAlignment="Top"/>
         <RadioButton x:Name="HelloButton" Content="Hello" HorizontalAlignment="Left" Margin="297,161,0,0" VerticalAlignment="Top"/>
         <RadioButton x:Name="GoodbyeButton" Content="Goodbye" HorizontalAlignment="Left" Margin="488,161,0,0" VerticalAlignment="Top"/>
    </Grid>
    

设置要默认选中的单选按钮

在这一步中,我们将 HelloButton 设置为默认选中,这样两个单选按钮中始终有一个处于选中状态。

  1. 在 XAML 视图中,找到 HelloButton 的标记。

  2. 添加 IsChecked 属性,并将其设置为“True”。 具体而言,添加 IsChecked="True"

    XAML 标记现在应类似于以下示例:

    <Grid>
         <TextBlock HorizontalAlignment="Left" Margin="252,47,0,0" TextWrapping="Wrap" Text="Select a message option and then choose the Display button." VerticalAlignment="Top"/>
         <RadioButton x:Name="HelloButton" Content="Hello" IsChecked="True" HorizontalAlignment="Left" Margin="297,161,0,0" VerticalAlignment="Top"/>
         <RadioButton x:Name="GoodbyeButton" Content="Goodbye" HorizontalAlignment="Left" Margin="488,161,0,0" VerticalAlignment="Top"/>
    </Grid>
    

最后添加的 UI 元素是一个 Button 控件。

添加按钮控件

  1. 在“工具箱”中,找到“按钮”控件,然后通过将控件拖到设计视图的窗体中,将其添加到 RadioButton 控件下方的设计界面中。 如果使用的是 Visual Studio 2019 或更高版本,则会出现一条红线,帮助你使控件居中。

  2. 在 XAML 视图中,将 Button 控件的“内容”值从 Content="Button" 更改为 Content="Display",然后保存更改。

    你的窗口应与下图类似。

    MainWindow form with control labels

    XAML 标记现在应类似于以下示例:

    <Grid>
         <TextBlock HorizontalAlignment="Left" Margin="252,47,0,0" TextWrapping="Wrap" Text="Select a message option and then choose the Display button." VerticalAlignment="Top"/>
         <RadioButton x:Name="HelloButton" Content="Hello" IsChecked="True" HorizontalAlignment="Left" Margin="297,161,0,0" VerticalAlignment="Top"/>
         <RadioButton x:Name="GoodbyeButton" Content="Goodbye" HorizontalAlignment="Left" Margin="488,161,0,0" VerticalAlignment="Top"/>
         <Button Content="Display" HorizontalAlignment="Left" Margin="377,270,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
    
  1. 在“工具箱”中,找到“按钮”控件,然后通过将控件拖到设计视图的窗体中,将其添加到 RadioButton 控件下方的设计界面中。 这些参考线可以帮助你将控件居中。

  2. 在 XAML 视图中,将 Button 控件的“内容”值从 Content="Button" 更改为 Content="Display",然后保存更改。

    你的窗口应类似于以下屏幕截图。

    Screenshot of the Design window for Greetings.xaml showing a TextBlock control, two RadioButton controls labeled 'Hello' and 'Goodbye', and a button labeled 'Display'.

    XAML 标记现在应类似于以下示例:

    <Grid>
         <TextBlock HorizontalAlignment="Left" Margin="252,47,0,0" TextWrapping="Wrap" Text="Select a message option and then choose the Display button." VerticalAlignment="Top"/>
         <RadioButton x:Name="HelloButton" Content="Hello" IsChecked="True" HorizontalAlignment="Left" Margin="297,161,0,0" VerticalAlignment="Top"/>
         <RadioButton x:Name="GoodbyeButton" Content="Goodbye" HorizontalAlignment="Left" Margin="488,161,0,0" VerticalAlignment="Top"/>
         <Button Content="Display" HorizontalAlignment="Left" Margin="377,270,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
    

向显示按钮添加代码

此应用程序运行时,用户选择单选按钮,再选择“显示” 按钮之后,会显示一个消息框。 选择 Hello 将显示一个消息框,选择 Goodbye 将显示另一个。 若要创建此行为,请将代码添加到 MainWindow.xaml.cs 中的 Button_Click 事件。

  1. 在设计图面上,双击 “显示” 按钮。

    此时,MainWindow.xaml.cs 打开,光标位于 Button_Click 事件上。

    private void Button_Click(object sender, RoutedEventArgs e)
    {
    
    }
    
  2. 输入以下代码:

    if (HelloButton.IsChecked == true)
    {
         MessageBox.Show("Hello.");
    }
    else if (GoodbyeButton.IsChecked == true)
    {
        MessageBox.Show("Goodbye.");
    }
    
  3. 保存应用程序。

此应用程序运行时,用户选择单选按钮,再选择“显示” 按钮之后,会显示一个消息框。 选择 Hello 将显示一个消息框,选择 Goodbye 将显示另一个。 若要创建此行为,请将代码添加到 MainWindow.xaml.cs 中的 Button_Click 事件。

  1. 在设计图面上,双击 “显示” 按钮。

    此时,MainWindow.xaml.cs 打开,光标位于 Button_Click 事件上。

    private void Button_Click(object sender, RoutedEventArgs e)
    {
    
    }
    

    双击“显示”按钮时,Click="Button_Click" 将添加到 XAML。

    XAML 标记现在应类似于以下示例:

    <Grid>
         <TextBlock HorizontalAlignment="Left" Margin="252,47,0,0" TextWrapping="Wrap" Text="Select a message option and then choose the Display button." VerticalAlignment="Top"/>
         <RadioButton x:Name="HelloButton" Content="Hello" IsChecked="True" HorizontalAlignment="Left" Margin="297,161,0,0" VerticalAlignment="Top"/>
         <RadioButton x:Name="GoodbyeButton" Content="Goodbye" HorizontalAlignment="Left" Margin="488,161,0,0" VerticalAlignment="Top"/>
         <Button Content="Display" HorizontalAlignment="Left" Margin="377,270,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    </Grid>
    
  2. 输入以下代码:

    if (HelloButton.IsChecked == true)
    {
         MessageBox.Show("Hello.");
    }
    else if (GoodbyeButton.IsChecked == true)
    {
        MessageBox.Show("Goodbye.");
    }
    
  3. 保存应用程序。

调试并测试应用程序

接下来将调试应用程序,查找错误并测试两个消息框是否正确显示。 下面的说明介绍如何生成和启动调试器,但以后可以阅读生成 WPF 应用程序 (WPF)调试 WPF 获取有关详细信息。

更改 MainWindow.xaml 的名称

为 MainWindow 指定更具体的名称。 在“解决方案资源管理器”中,右键单击“MainWindow.xaml”,然后选择“重命名”。 将该文件重命名为“Greetings.xaml”。

查找并修复错误

在此步骤中,将遇到之前因更改 MainWindow.xaml 文件的名称而引起的错误。

开始调试和查找错误

  1. 通过按 F5或选择“调试”,然后选择“启动调试”,启动调试程序。

    此时将出现“中断模式”窗口,“输出”窗口指示“发生 IOException: 找不到资源 mainwindow.xaml”。

    IOException message

  2. 依次选择“调试”>“停止调试”,停止调试程序。

我们将 MainWindow.xaml 重命名为 Greetings.xaml,但是该代码仍然引用 MainWindow.xaml 作为应用程序的启动 URI,因此该项目无法启动。

  1. 通过按 F5或选择“调试”,然后选择“启动调试”,启动调试程序。

    此时将出现“中断模式”窗口,“输出”窗口指示“发生 IOException: 找不到资源 mainwindow.xaml”。

    Screenshot of the Output window showing a System.IO.IOException with the message, Cannot locate resource mainwindow.xaml.

  2. 依次选择“调试”>“停止调试”,停止调试程序。

开始学习本教程时,我们将 MainWindow.xaml 重命名为 Greetings.xaml,但是该代码仍然引用 MainWindow.xaml 作为应用程序的启动 URI,因此该项目无法启动。

将 Greetings.xaml 指定为启动 URI

  1. 在“解决方案资源管理器”中,打开“App.xaml”文件。

  2. StartupUri="MainWindow.xaml" 更改为 StartupUri="Greetings.xaml",然后保存更改。

作为一个可选步骤,将应用程序窗口标题更改为匹配此新名称可以避免混淆。

  1. 在“解决方案资源管理器”中,打开刚刚重命名的 Greetings.xaml 文件。

  2. 将 Window.Title 属性的值从 Title="MainWindow" 更改为 Title="Greetings",然后保存更改。

再次启动调试程序 (按“F5”)。 你现在应该可以看到应用程序的 Greetings 窗口。

Screenshot of running app

Screenshot of the Greetings window with the TextBlock, RadioButtons, and Button controls visible. The 'Hello' radio button is selected.

现在关闭应用程序窗口,停止调试。

使用断点进行调试

可通过添加一些断点,在调试期间测试代码。 可以通过选择“调试”>“切换断点”、通过在编辑器中想要添加断点的代码行旁边的左边距中单击或按 F9 来添加断点。

添加断点

  1. 打开“Greetings.xaml.cs”,并选择以下行:MessageBox.Show("Hello.")

  2. 通过选择 “调试” -> “切换断点” ,从菜单中添加断点。

    编辑器窗口最左侧边距中该代码行附近将显示一个红圈。

  3. 选择以下行: MessageBox.Show("Goodbye.")

  4. 按“F9”键添加断点,然后按“F5”启动调试。

  5. “Greetings” 窗口中,选择 “Hello” 单选按钮,然后选择 “显示” 按钮。

    MessageBox.Show("Hello.") 将用黄色突出显示。 在 IDE 底部,“自动”、“本地”和“监视”窗口一起停靠在左侧,而“调用堆栈”、“断点”、“异常设置”、“命令”、“即时”和“输出”窗口一起停靠在右侧。

    Breakpoint in the debugger

  6. 在菜单栏上,选择“调试”>“跳出”。

    应用程序继续执行,并将显示出带有“Hello”的消息框。

  7. 选择消息框上的 “确定” 按钮将其关闭。

  8. “Greetings” 窗口中,选择 “Goodbye” 单选按钮,然后选择 “显示” 按钮。

    MessageBox.Show("Goodbye.") 将用黄色突出显示。

  9. 按“F5”键继续调试。 当消息框出现时,选择消息框上的 “确定” 按钮将其关闭。

  10. 关闭应用程序窗口,停止调试。

  11. 在菜单栏上,选择“调试”>“禁用所有断点”。

  1. 打开“Greetings.xaml.cs”,并选择以下行:MessageBox.Show("Hello.")

  2. 通过选择 “调试” -> “切换断点” ,从菜单中添加断点。

    编辑器窗口最左侧边距中该代码行附近将显示一个红圈。

  3. 选择以下行: MessageBox.Show("Goodbye.")

  4. 按“F9”键添加断点,然后按“F5”启动调试。

  5. “Greetings” 窗口中,选择 “Hello” 单选按钮,然后选择 “显示” 按钮。

    MessageBox.Show("Hello.") 将用黄色突出显示。 在 IDE 底部,“自动”、“本地”和“监视”窗口一起停靠在左侧,而“调用堆栈”、“断点”、“异常设置”、“命令”、“即时”和“输出”窗口一起停靠在右侧。

    Screenshot of a debug session in Visual Studio. The code window for Greetings.xaml.cs shows execution stopped at a breakpoint with a line highlighted in yellow.

  6. 在菜单栏上,选择“调试”>“跳出”。

    应用程序继续执行,并将显示出带有“Hello”的消息框。

  7. 选择消息框上的 “确定” 按钮将其关闭。

  8. “Greetings” 窗口中,选择 “Goodbye” 单选按钮,然后选择 “显示” 按钮。

    MessageBox.Show("Goodbye.") 将用黄色突出显示。

  9. 按“F5”键继续调试。 当消息框出现时,选择消息框上的 “确定” 按钮将其关闭。

  10. 关闭应用程序窗口,停止调试。

  11. 在菜单栏上,选择“调试”>“禁用所有断点”。

查看 UI 元素的表示形式

在正在运行的应用中,你会看到窗口顶部显示了一个小组件。 该小组件是一个运行时帮助程序,通过它可以快速访问一些有用的调试功能。 选择第一个按钮“转到实时可视化树”。 随即会看到一个包含一个树的窗口,树中包含页面的所有可视元素。 展开节点,找到你添加的按钮。

Screenshot of Live Visual Tree window

Screenshot of the Live Visual Tree window, showing the tree of visual elements in HelloWPFApp.exe while it's running.

生成应用程序的发布版本

确认一切就绪后,可以准备该应用程序的发布版本。

  1. 在主菜单中,依次选择“生成”>“清理解决方案”,删除上一生成过程中创建的中间文件和输出文件。 此步骤不是必需的,但它可以清理调试生成输出。

  2. 使用工具栏(当前显示“调试”)上的下拉列表控件把 HelloWPFApp 的生成配置从“调试”更改为“发布” 。

  3. 选择“生成”>“生成解决方案”来生成解决方案 。

恭喜你完成本教程! 可在解决方案和项目目录 (...\HelloWPFApp\HelloWPFApp\bin\Release) 下找到生成的 .exe 文件。

后续步骤

恭喜你完成本教程! 若要了解详情,请继续学习后续教程。

请参阅