.NET Core 创建 UWP 应用程序
UWP,Universal 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 文件中输入代码。

<Pagex:Class = "UWPFirstApp.MainPage"xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local = "using:UWPFirstApp"xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"mc:Ignorable = "d"><Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"><StackPanel HorizontalAlignment = "Center"><TextBlock Text = "Hello, world!"Margin = "20"Width = "200"HorizontalAlignment = "Left"/><TextBlock Text = "Write your name."Margin = "20"Width = "200"HorizontalAlignment = "Left"/><TextBox x:Name = "txtbox"Width = "280"Margin = "20"HorizontalAlignment = "Left"/><Button x:Name = "button" Content = "Click Me"Margin = "20"Click = "button_Click"/><TextBlock x:Name = "txtblock"HorizontalAlignment = "Left"Margin = "20"/></StackPanel></Grid></Page>
下面是 C# 中按钮的点击事件。
using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.InteropServices.WindowsRuntime;using Windows.Foundation;using Windows.Foundation.Collections;using Windows.UI.Xaml;using Windows.UI.Xaml.Controls;using Windows.UI.Xaml.Controls.Primitives;using Windows.UI.Xaml.Data;using Windows.UI.Xaml.Input;using Windows.UI.Xaml.Media;using Windows.UI.Xaml.Navigation;namespace UWPHellowWorld {/// <summary>/// 可以单独使用或在框架内导航到的空页面。/// </summary>public sealed partial class MainPage : Page {public MainPage() {this.InitializeComponent();}private void button_Click(object sender, RoutedEventArgs e) {if (txtbox.Text != "")txtblock.Text = "Hello: " + txtbox.Text;elsetxtblock.Text = "You have not write your name";}}}
现在让我们在本地机器上运行上述代码,您将看到下面的窗口。现在在文本框中键入任何名称,然后按 Click Me 按钮。