WPF新建工程
1. 新建WPF窗体应用程序
新建工程,选择WPF应用程序,下方输入工程名称,选择工程位置
工程新建成功后如下图所示:
2. 常用文件格式说明
xaml文件是WPF程序的窗体文件,通常我们在xaml文件中设计我们的窗体,其对应的cs文件是窗体的后台逻辑。工程新建成功后,系统会自动生成几个文件,这里详细解释一下App.xaml,App.xaml.cs,MainWindow.xaml文件和MainWindow.xaml.cs文件。
App.xaml文件:
<Application x:Class="wpfbase.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:wpfbase"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
Application是应用类类型,x:Class="wpfbase.App"的意义即是从Application类中派生出一个wpfbase.App类,wpfbase是APP类所在的命名空间,也就是,这里实际上是声明了一个wpfbase.App类。
“xmlns”是属于强制关键字,被用来声明一个命名空间。其语法结构为“xmlns:”+“命名空间前缀名”,而对于默认命名空间,无需定义命名空间前缀名。
xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=“http://schemas.microsoft.com/winfx/2006/xaml”
以上两个命名空间是Visual Studio 15创建默认项目时自动生成的,其中实例化了所需要的公共类库。
xmlns:local="clr-namespace:wpfbase"即把wpfbase后台命名空间映射到窗体的local空间
StartupUri="MainWindow.xaml"指定了启动窗口为MainWindow.xaml。
App.xaml.cs文件:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace wpfbase
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
}
}
前面提到,xaml文件已经在wpfbase命名空间中声明了一个App类,所以在后台.cs文件中,使用了partial关键字,这个关键字可以使类在多处声明而不冲突。
MainWindow.xaml文件:
<Window x:Class="wpfbase.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:wpfbase"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
</Grid>
</Window>
刚刚App.xaml已经指定了MainWindow.xaml为启动窗口,所以程序运行时也是从这个窗体启动。
MainWindow.xaml.cs文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace wpfbase
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
cs文件为其对应的后台