下载Visual Studio
新建WPF模板
在搜索框输入“WPF”,选择“WPF应用(.NET Framework)”
创建成功,MainWindow.xaml是UI界面,在这个界面设计控件的属性,在MainWindow.xaml.cs后台文件中也可以对UI界面控件的属性进行修改。MainWindow.xaml.cs文件是后台用来实现逻辑的,比如说,在UI界面定义了按钮Button的点击(Click)功能属性,此时点击按钮就不会触发任何事件,如果在MainWindow.xaml.cs文件中对点击(Click)事件实现了点击按钮弹出一个对话框,那么你点击按钮之后就会弹出一个对话框。
实现:按下按钮,弹出一个对话框,对话框显示“This is my first WpfApp”
1、打开工具箱,找到Button控件,拖拽至UI界面
2、在XAML文件中就会出现<Button / >标签,可在里面修改Button的属性
3、在Button标签中添加点击事件Click = Button_Click,在下方会弹出一个“<新建事件处理程序>”,这是检测到在MainWindow.xaml.cs文件中未找到该方法,双击“<新建事件处理程序>”,cs文件中就会自动创建该方法。
4、在Button_Clicko方法中定义实现的逻辑
MessageBox.Show("This is my first WpfApp");
完整的代码
//MainWindow.xaml
<Window x:Class="FirstWPF.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:FirstWPF"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="100,70,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
</Window>
//MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using