这是在VS中为Windows窗体应用程序使用的传统方法。它通过代码语句生成用户界面。
1.创建一个类,名称改为:Window1.cs
代码如下:
using System.Windows; using System.Windows.Controls; using System.Windows.Markup; namespace WpfApp { internal class Windows1:Window { private Button button1; public Windows1() { InitializeComponent(); } private void InitializeComponent() { //设置窗体 this.Width = 285; this.Height = 285; this.Left = this.Top = 100; this.Title = "Code-Only Window"; //创建停靠面板对象 DockPanel panel = new DockPanel(); //创建按钮对象 button1 = new Button(); button1.Content = "Please click me."; button1.Margin = new Thickness(30); button1.Click += button1_Click; IAddChild container= panel; container.AddChild(button1); container = this; container.AddChild(panel); } private void button1_Click(object sender, RoutedEventArgs e) { button1.Content = "Thank you"; } } }
2.创建第二个类:Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace WpfApp { internal class Program:Application { [STAThread()] static void Main() { Program app = new Program(); app.MainWindow=new Windows1(); app.MainWindow.ShowDialog(); } } }
3.删除App.xaml
运行效果图: