.NET Core 创建 UWP 应用程序

UWPUniversal Windows Platform,即通用 Windows 平台。

在本章中,我们将讨论如何使用 .NET Core 创建 UWP 应用程序。UWP 也称为 Windows 10 UWP 应用程序。此应用程序不会在旧版本的 Windows 上运行,但只会在将来版本的 Windows 中运行。

如果你想在本地运行它,你必须有 Windows 10,你也可以在 Windows 8 上开发,然后你需要在 Emulator 虚拟机上运行它,所以建议使用 Windows 10。

  • 打开 Visual Studio,然后在 "启动" 窗口上,选择 "创建新项目"。

  • 在 "创建新项目" 屏幕上,在搜索框中输入 "通用 Windows",选择 "空白应用(通用 Windows)" 对应的 C# 模板 ,然后选择 "下一步"。如果搜索 "通用 Windows" 结果为空,那么请先进行如下步骤:

    • 点击 "安装多个工具和功能"

    • 安装 "通用 Windows 平台开发" 如下:

  • 输入项目名称 "UWPFirstApp" 接受 "新式通用 Windows 平台项目" 对话框中的默认目标版本和最小版本设置受 "新式通用 Windows 平台项目" 对话框中的默认目标版本 和最小版本 设置。

注意:如果你是第一次使用 Visual Studio 创建 UWP 应用,则可能会出现 "设置" 对话框。选择 "开发人员模式",然后选择 "是"。

回到 Visual Studio,在 MainPage.XAML 文件中输入代码。

  1. <Page
  2. x:Class = "UWPFirstApp.MainPage"
  3. xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  4. xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
  5. xmlns:local = "using:UWPFirstApp"
  6. xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
  7. xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
  8. mc:Ignorable = "d">
  9. <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
  10. <StackPanel HorizontalAlignment = "Center">
  11. <TextBlock Text = "Hello, world!"
  12. Margin = "20"
  13. Width = "200"
  14. HorizontalAlignment = "Left"/>
  15. <TextBlock Text = "Write your name."
  16. Margin = "20"
  17. Width = "200"
  18. HorizontalAlignment = "Left"/>
  19. <TextBox x:Name = "txtbox"
  20. Width = "280"
  21. Margin = "20"
  22. HorizontalAlignment = "Left"/>
  23. <Button x:Name = "button" Content = "Click Me"
  24. Margin = "20"
  25. Click = "button_Click"/>
  26. <TextBlock x:Name = "txtblock"
  27. HorizontalAlignment = "Left"
  28. Margin = "20"/>
  29. </StackPanel>
  30. </Grid>
  31. </Page>

下面是 C# 中按钮的点击事件。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Runtime.InteropServices.WindowsRuntime;
  6. using Windows.Foundation;
  7. using Windows.Foundation.Collections;
  8. using Windows.UI.Xaml;
  9. using Windows.UI.Xaml.Controls;
  10. using Windows.UI.Xaml.Controls.Primitives;
  11. using Windows.UI.Xaml.Data;
  12. using Windows.UI.Xaml.Input;
  13. using Windows.UI.Xaml.Media;
  14. using Windows.UI.Xaml.Navigation;
  15. namespace UWPHellowWorld {
  16. /// <summary>
  17. /// 可以单独使用或在框架内导航到的空页面。
  18. /// </summary>
  19. public sealed partial class MainPage : Page {
  20. public MainPage() {
  21. this.InitializeComponent();
  22. }
  23. private void button_Click(object sender, RoutedEventArgs e) {
  24. if (txtbox.Text != "")
  25. txtblock.Text = "Hello: " + txtbox.Text;
  26. else
  27. txtblock.Text = "You have not write your name";
  28. }
  29. }
  30. }

现在让我们在本地机器上运行上述代码,您将看到下面的窗口。现在在文本框中键入任何名称,然后按 Click Me 按钮。