When it comes to WPF projects, you'll certainly think of XAML, which is complementary to each other, so you can create a WPF project that doesn't use XAML, and today we'll talk about three different ways to encode a WPF application.
1. use code only : This approach is similar to a traditional Windows Forms application that generates a user interface through code statements. This approach is uncommon when writing WPF projects, but not entirely without merit, and its potential advantage is the ability to customize the application at will. For example, if you want to create a form with code, you need to make a new class (note not to create a new window), inherit the window in class code, and then write a method that initializes the control.
PrivatvoidInitcontrols () {DockPanel panel=NewDockPanel (); button btn=Newbutton;btn. Content="Click Me"; btn. Click+=btn_click;iaddchild Container=Panel;container. AddChild (BTN); container= This; container. AddChild (panel);}Private voidBtn_click (ObjectSender,routedeventargs e) {btn. Content="OK";}
2. using code and non-compiled XAML: This approach is to build the XAML class separately in the project and then parse it through the XamlReader class in your code. This approach is useful for dynamic generation of interfaces in some cases. Just like the project I was working on, I needed to generate the GridView columns dynamically based on the data, and the columns were not necessarily the same, the properties of the column bindings were based on the data, I looked for some methods, but eventually decided to use the XAML markup to write dynamically in the background code. The method I'm using is more complex than importing a XAML file directly, but the idea is the same, and it's using the XamlReader class parsing.
<dockpane xmlns=:"http://schemas.microsoft.com/winfx/2006/xaml/presentation" > <button name="btn"> Clickme</Button></DockPanel>
Public Window (string xamlfile) {DependencyObject rootelement; using (FileStream fs=new FileStream (Xamlfile,filemode.open)) {rootelement=(DependencyObject) Xamlreader.load (fs);} this. content=rootelement;btn1= (button) Logicaltreehelper.fiindlogicalnode (rootelement,"btn "); btn1. Click+ =btn_click;}
3. using code and compiled XAML: This is a common method, such as creating a new Window in a project, automatically associating a XAML file, and the Window.cs file automatically generates a method to initialize the control.
Three ways to create WPF applications with WPF learning