练习 - 编写 UWP 应用

已完成

Screenshot that shows the UWP, WPF, and Windows Forms logo.

Visual Studio 中的通用 Windows 平台 (UWP) 是一项技术,可确保一个应用在所有设备上都能运行:台式机、笔记本电脑、平板电脑、Xbox、Surface Hub 或 HoloLens 设备。 针对 UWP 进行开发与针对 Windows Presentation Foundation (WPF) 进行开发之间有很多相似之处,但也有一些细微差别。 本教程介绍了这些差别,同时也是进入 UWP 编程世界的第一步。

在本单元中,我们会:

  • 使用 Visual Studio 创建新的 UWP 项目。
  • 将 UI 和代码元素添加到项目中,创建“hello world”程序的有趣变体。 每次选中“Say hello”按钮时,“Hello there!”文本和边框都会随机改变颜色。
  • 了解如何设置属性和创建事件。

备注

假设你已在计算机中安装了 Windows 和 Visual Studio 2022,如学习模块“Windows 10 开发简介”中所述。

UWP“Say hello”教程

创建项目

  1. 打开“Visual Studio”,依次选择菜单中的“文件”>“新建”>“项目”。 然后,选择“C#”作为项目语言。 接下来,选择“空白应用(通用 Windows)”项目类型。 在“名称”字段中,输入易记名称,如 SayHello。 完成操作后,选择“创建”

    注意

    当“新建通用 Windows 平台项目”对话框提示你选择 UWP 的“目标版本”和“最低版本”这些选项时,只需选择“确定”。 默认选择适用于此项目。

    Screenshot that shows the Configure your new project window for a Blank App (Universal Windows) with the create button selected.

  2. 在项目打开后,最好确保“解决方案资源管理器”和“属性”窗格处于打开状态。 默认情况下,这两个窗格位于 Visual Studio 的右侧。 如果它们不可见,请打开“视图”菜单,并选择这两个窗格。

  3. 在“解决方案资源管理器”中,确保能看到要处理的两个文件的文件名:MainPage.xaml 及其代码隐藏文件 MainPage.xaml.cs。 选择“MainPage.xaml”,以打开它。

    Screenshot that shows the MainPage.xaml and MainPage.xaml.cs files in a red box in Solution Explorer.

设计 UI

  1. 如果“工具箱”面板尚未打开,请选择“视图”菜单,然后选择“工具箱”。 在“工具箱”中,选择“常见 XAML 控件”

    Screenshot that shows the Toolbox menu in Visual Studio with Button and TextBox in red boxes.

  2. 将“按钮”拖到设计器布局的下半部分。 然后,将“文本框”拖到布局的上半部分,并将它的四角向外拖出一点,如下所示:

    Screenshot that shows a button dragged onto the design layout.

    注意

    请注意按钮和工具箱条目是如何添加到布局下方 XAML 定义中的 <Grid> 内的。

  3. 现在,要对这些 UI 元素设置一些属性。 选择按钮,这样它的属性就会显示在“属性”窗格中。 将“名称”更改为“SayHelloButton”等简单名称,并将(展开“常见”后显示的)“内容”更改为“Say hello”。

    Screenshot that shows the Name and Content properties set in the Properties window.

    注意

    请注意如何将 Name 属性添加到布局下方的 XAML 定义中的 Button 项。 在设计器中更改属性时,XAML 定义会自动更新。

  4. 需要向按钮附加事件。 可以选择按钮本身,但这仅在设计器布局处于所需状态时才有效。 输入事件的更确切方式是,打开适用于相应 UI 项的事件。 为此,可以选择“属性”窗格中显示的图标(如下所示),然后选择 Click 事件的条目。 这样做会自动创建已命名事件“SayHelloButton_Click”,在 MainPage.xaml.cs 文件中添加相应的代码条目,并为你打开文件。

    Screenshot that shows the Events pane selected in the Properties window, and the Click event in a red box.

  5. 我们暂时不会输入任何代码,因此请在主视图中选择“MainPage.xaml”。 现在继续处理 UI。

  6. 选择在设计器中创建的文本框,以显示它的属性。 我们将对文本框的属性进行不少更改。 如果事件显示在“属性”窗格中,请选择名称旁边的扳手图标,以返回到命名属性。

  7. 将“名称”条目更改为“textBox1”,然后在“布局”属性中将“宽度”和“高度”分别更改为“360”和“80”。

    Screenshot that shows the Layout properties of Width and Height set in the Properties window.

  8. 折叠“布局”部分。

  9. 在“文本”大小列表中,将磅值更改为“36”,好看又清楚!

    Screenshot that shows the Name set as textBox1 in the properties, and the Tex tab open with 36px selected as the text size.

  10. “文本”部分默认打开标记为“A”的字体选项卡。 选择段落图标,并将对齐方式更改为“居中”。

    Screenshot that shows the paragraph tab under the Text menu selected, and Center selected as the paragraph justification.

  11. 折叠“文本”部分,并展开“外观”。 选择外观属性公开列表底部的向下箭头,以显示完整列表。 将左边框和上边框的厚度更改为“1”,将右边框和下边框的厚度更改为“8”。 现在框带有一点投影效果了!

    Screenshot that shows the Appearance menu expanded in the Properties window, with the BorderThickness settings in a red box.

  12. 折叠“外观”,并展开“常见”。 输入文本框的文本:如“Hello there!”等易记文本。

    Screenshot that shows the Common menu expanded in the Properties window, with Hello there entered in the Text property.

即将完成设置应用的 UI 元素。 XAML 文件中的<Grid>条目应如下所示:

Screenshot that shows an example of the the XAML file, with a Button and TextBox element inside the Grid element. All of the Button and Textbox properties are displayed.

注意

郑重声明一下,可以直接编辑 XAML(更改数值或添加整个 UI 元素)。 本教程不执行此操作。

编写代码隐藏文件

  1. 现在可以从设置 UI 转为编写应用代码了。 是时候重新打开“MainPage.xaml.cs”文件了。 从主视图上方或解决方案资源管理器中选择文件。 类 MainPage 应如下所示:

    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
    
        private void SayHelloButton_Click(object sender, RoutedEventArgs e)
        {
    
        }
    }
    
  2. 接下来,将确保有所有必要的 using 语句。 检查是否有以下语句;如果没有,请添加。 特别要确保其中有 using Windows.UI; 语句。 编辑完文件后,可视需要选择删除 Visual Studio 在创建项目时包含的任何不必要 using 语句。 未使用的命名空间显示为灰色。

    using System;
    using Windows.UI;
    using Windows.UI.Xaml;
    using Windows.UI.Xaml.Controls;
    using Windows.UI.Xaml.Media;
    
  3. 每当选择按钮时,应用都会以随机颜色呈现 hello 文本。 因此,需要添加类级别 Random 对象,以及随机填充 RGB 设置值的 GetRandomBytes 方法。 剪切并粘贴或自己键入下面的代码,以确保类 MainPage 如下所示:

    public sealed partial class MainPage : Page
    {
        private Random rand;
    
        public MainPage()
        {
            this.InitializeComponent();
            rand = new Random();
        }
    
        private byte[] GetRandomBytes(int n)
        {
            // Fill an array of bytes of length "n" with random numbers.
            var randomBytes = new byte[n];
            rand.NextBytes(randomBytes);
            return randomBytes;
        }
    
        private void SayHelloButton_Click(object sender, RoutedEventArgs e)
        {
    
        }
    }
    
  4. 最后,需要通过按钮单击事件调用 GetRandomBytes,根据返回的字节数组中创建随机颜色,再将文本框属性更改为此颜色。 完成的 SayHelloButton_Click 方法应如下所示:

        private void SayHelloButton_Click(object sender, RoutedEventArgs e)
        {
            byte[] rgb = GetRandomBytes(3);
    
            // Create a solid color brush using the three random numbers.
            var randomColorBrush = new SolidColorBrush(Color.FromArgb(255, rgb[0], rgb[1], rgb[2]));
    
            // Set both the text color and the text box border to the random color.
            textBox1.BorderBrush = randomColorBrush;
            textBox1.Foreground = randomColorBrush;
        }
    
  5. 请花一两秒钟时间来检查代码。 如果任何内容有红色下划线,表明有地方存在问题。 可能是单词拼写错误,也可能是代码片段放错了位置。

运行

接下来,将编译并运行程序!

  1. 在 Visual Studio 中的“调试”菜单上,选择“开始执行(不调试)”,或者仅选择 F5 键。 如果所有内容都已正确输入,你应会看到一个正在运行的应用,如下所示:

    Screenshot that shows the app running. Hello there displays with green text in a green box with the Say hello button below it.

  2. 反复选择“Say hello”按钮,可以看到“Hello there!”文本和边框会随机改变颜色。

如果能看到,那就大功告成了! 你已完成本教程。 如果没有看到,请仔细重新检查代码和 UI 属性设置,看看哪里出错了。