三個方式來實現wpf的應用程序app
1/只使用代碼ide
好處:就是隨意的定製應用程序,相比之下xaml文檔,它們只能做爲固定的不變的資源嵌入到程序集中函數
壞處:由於wpf控件包含沒有參數的構造函數,因此一個簡單的控件就可寫不少代碼this
demo:lua
新建一個普通類(不是窗口類)spa
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.Markup; namespace WPF_Valuable { class Window1:Window { private Button button1; public Window1() { InitializeComponent(); } private void InitializeComponent() { //configure the form this.Width = this.Height = 285; this.Left = this.Top = 100; this.Title = "Code-only Window"; //creater a container to hold a button DockPanel panel = new DockPanel(); //Creater a button. button1 = new Button(); button1.Content = "Please click me"; button1.Margin = new System.Windows.Thickness(30); //Attach the event handler button1.Click += button1_Click; IAddChild container = panel; container.AddChild(button1); container = this; container.AddChild(panel); } void button1_Click(object sender, RoutedEventArgs e) { //throw new NotImplementedException(); button1.Content = "Thank you "; } } }
二,使用代碼xamlcode
1 public class Window1 : Window 2 { 3 private Button button1; 4 5 public Window1(string xamlFile) 6 { 7 InitializeComponent(xamlFile); 8 } 9 10 private void InitializeComponent(string xamlFile) 11 { 12 // Configure the form. 13 this.Width = this.Height = 285; 14 this.Left = this.Top = 100; 15 this.Title = "Dynamically Loaded XAML"; 16 17 // Get the XAML content from an external file. 18 DependencyObject rootElement; 19 using (FileStream fs = new FileStream(xamlFile, FileMode.Open)) 20 { 21 rootElement = (DependencyObject)XamlReader.Load(fs); 22 } 23 24 // Insert the markup into this window. 25 this.Content = rootElement; 26 27 // Find the control with the appropriate name. 28 //button1 = (Button)LogicalTreeHelper.FindLogicalNode(rootElement, "button1"); 29 FrameworkElement frameworkElement = (FrameworkElement)rootElement; 30 button1 = (Button)frameworkElement.FindName("button1"); 31 32 // Wire up the event handler. 33 button1.Click += new RoutedEventHandler(button1_Click); 34 } 35 36 private void button1_Click(object sender, RoutedEventArgs e) 37 { 38 button1.Content = "Thank you."; 39 }
// First approach: window with XAML content.
Window1 window1 = new Window1("Window1.xaml");
window1.Show();orm