第一步把创建的WPF项目的原来的MainWindow和app文件删除了。新创建两个类一个是window1一个是Program类
window1的代码:
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
namespace WpfApplication2
{
class window1 : Window
{
private Button button1;
public window1()
{
InitializeComponent();
}
private void InitializeComponent()
{
//设置窗体
this.Width = 285;
this.Height = 250;
this.Left = this.Top = 100;
this.Title = "Code-Only Window";
//创建停靠面板对象
DockPanel panel = new DockPanel();
//创建按钮对象
button1 = new Button();
button1.Content = "Pleace click me.";
button1.Margin = new Thickness(30,30,30,30); //也可以写一个30
button1.Click += button1_Click1;
IAddChild container = panel;
container.AddChild(button1);
container = this;
container.AddChild(panel);
}
private void button1_Click1(object sender, RoutedEventArgs e)
{
button1.Content = "Thank you";
}
}
}
Program中的代码:
using System;
using System.Windows;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WpfApplication2
{
class Program : Application
{
[STAThread()]
static void Main()
{
Program app = new Program();
app.MainWindow = new window1();
app.MainWindow.ShowDialog();
}
}
}
效果: