Building a simple WPF program using code may have multiple code structures:
1. The simplest. You can see the following code: mywindow inherits from the window class, create an application instance in the entry function, and call the window using the run method of this object.
The show method of the instance. This implementation method is too readable and confusing.
using System;
using System.Windows;
namespace WpfAppByCode
{
class MyWindow : Window
{
[STAThread]
public static void Main()
{
new Application().Run(new MyWindow());
}
}
}
To be continued ......
PS: Window instance location settings
Many readers may first think of windowstartuplocation enumeration-isn't windowstartuplocation a constant assigned to windowstartuplocation enumeration for the windowstartuplocation attribute of the window instance? For a smart reader, have you ever thought about the specific implementation? In fact, the properties related to the location of the window instance include width, height, left, and top, which are sequential. Generally, we have to assign values to width and height before specifying the left and top attributes. Otherwise, our code will become invalid, it is possible that our intention is to center the window, but after compiling and running it, we find that the window appears in the default position of the system (windowstartuplocation. manual ). Note that if the width and height attributes are not specified in the window constructor, do not specify the left and top attributes in the constructor, it should be specified in the event processor of the loaded event of the window instance.
Using system;
Using system. windows;
Namespace wpfappbycode
{
Class inheritwindow: Window
{
[Stathread]
Public static void main ()
{
New Application (). Run (New inheritwindow ());
}
Public inheritwindow ()
{
This. Title = "scarecrow ";
This. Loaded + = windowonloaded;
}
Private void windowonloaded (Object sender, routedeventargs E)
{
This. Left = (systemparameters. primaryscreenwidth-This. actualwidth)/2;
This. Top = (systemparameters. primaryscreenheight-This. actualheight)/2;
}
}
}