首先梳理一下WPF应用程序的框架(和MFC的)
- WPF应用程序APP
- 程序的Windows窗口,其中也包括MainWindows主窗口
- 窗口的属性,包括大小、标题、位置等属性
- 窗口的容器组件,用于存放各种其他组件
- 容器的布局属性
- 组件1
- 组件的属性,比如大小、位置、内容等
- 组件的响应程序
- 组件2
- 组件3
- 程序的Windows窗口,其中也包括MainWindows主窗口
这些结构是我大致根据学习视频总结的。
那么我们用代码创建WPF应用程序的时候,这些对应的结构元素也需要一一创建。
我们首先自己建一个窗口的类,继承Window类,命名为Window1,然后进行代码编辑创建元素
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
namespace _02.create_wpf_by_code
{
class Window1 : Window
{
private Button button1;
public Window1()
{
InitializeComponent();
}
private void InitializeComponent()
{
//设置窗体大小
this.Width = 285; this.Height = 250;
this.Left = 100; this.Top = 100;
this.Title = "Create Window By Code";
//创建一个停靠面板对象,用来放组件
DockPanel panel = new DockPanel();
//创建按钮对象
button1 = new Button();
button1.Content = "点击";
button1.Margin = new Thickness(30);
//添加事件处理程序
button1.Click += btn1_Click;
//将按钮添加到面板中
IAddChild container = panel;
container.AddChild(button1);
//将面板添加到Window窗体中
container = this;
container.AddChild(panel);
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
button1.Content = "成功";
}
}
}
然后我们新建一个APP的类,继承Application类,命名为Program,用来作为应用程序的启动项 ,并且在该类中对App的主窗口进行赋值,将主窗口的值用我们上面创建好的窗口类Window1进行实例化,这样程序启动的时候,主窗口就会是我们的Window1这个类窗口了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace _02.create_wpf_by_code
{
class Program : Application
{
[STAThread()]//单线程
static void Main()
{
Program app = new Program();
app.MainWindow = new Window1();
app.MainWindow.ShowDialog();
}
}
}
最后设置一下项目的启动项,右键项目点击属性,在启动对象这一栏下拉选择我们之前新建的App类Program即可
最后是运行效果