Self-taught WPF series (1)

Source: Internet
Author: User
Tags new set
Introduction

I have been using WPF for more than six months. It is time to write some basic knowledge about WPF. I have written several articles on this topic. They are all completed based on specific issues. Now, I will give you an understanding of how/why WPF has taken us as a revolutionary UI development.

As this is an article suitable for beginners and intermediate programmers, I will try to give as many basic examples as possible.

Windows presectation Foundation

As shown in the name, WPF is actually several frameworks introduced by. Net framework3.0. It actually proposes a new set of classes and assembly and allows us to program more effectively and flexibly. It uses direct3d rendering and a video card to display on the display. Therefore, this form of drawing is smooth and has the opportunity to take advantage of the hardware capabilities installed on your machine. Traditional GDI applications cannot use advanced graphics processing capabilities. Therefore, Windows Forms applications are always inefficient than WPF applications. Another important thing I must note is that the GDI windows form application uses the operating system control to establish its application. Therefore, it is basically difficult to customize them in your application. The WPF control is actually drawn on your screen. Therefore, if necessary, you can completely customize the control and modify its behavior.

Features of WPF

WPF has many advantages. Let me introduce the following:

Pixels unrelated to devices (DPI)

WPF introduces device-independent DPI settings for applications to build applications. For a window, it is very important to calculate how much DPI can be drawn on the screen. This is usually determined by the DPI settings of hardware devices and operating systems and device applications where applications are running. Any user can customize these settings, making the reference program look bad. The Windows form application uses a pixel-based method to change the size and appearance of each widget when DPI settings are changed.

WPF solves this problem and enables it to be independent from the computer's DPI settings. Let's see how it works:

For example, as shown in, you have drawn a box with a 1 inch-inch 96 DPI screen. Now, if you see the same application set with 120dpi, the box will become smaller. This is because what we see on the screen is completely dependent on DPI settings.

In WPF, this modification adopts the density-based method. This means that when the pixel density is modified, the element will adjust them accordingly so that the WPF application project is a device-independent pixel. As you can see on the way, when the WPF control requires more pixels, such as 120dpi, the application can adjust it appropriately to keep its size unchanged.

Built-in support for graphics and animation

As an environment rendering of DirectX, the WPF application is mainly supported by graphics and animation functions. There is a separate set of classes to process animation effects and graphics. The images drawn on the screen are also vector-based and object-oriented. This means that when you draw a rectangle in a WPF application, you can easily delete it from the screen and think that rectangle is actually an object you have always been in control. In traditional Windows-based applications, when you draw a rectangle, you cannot select it separately. Therefore, the WPF program design is completely different from the traditional windows program design and is more complex. We will discuss more details about graphics and animations later.

Redefinition of style and control templates

In addition to graphics and animation capabilities, WPF also comes with great flexibility to define styles and control templates. The style-based technology is similar to the CSS you may have encountered. It is a set of definitions. It defines what the control looks like when it is rendered to the screen. In traditional Windows applications, styles are tightly coupled with each control, so you need to define colors, styles, and so on for each separate control to make it look different. For WPF, styles and uielements are completely separated. Once you define a style, you can apply it to this element and you can change its appearance and style.

Generally, most of the uielemnet we process is actually not just an element. WPF references a new concept of a template. You can use it to redefine the entire control. For example, you have a checkbox with a rectangle and contentpresenter (where textbox is displayed ). then you can redefine your checkbox and put a togglebutton in it to make the check look more like a togglebutton rather than a rectangle. This is very interesting. In subsequent articles, we will explore the details of more restrictive and control templates.

Resources available for each control

Another important feature of WPF is the accessible resources. In traditional Windows applications, it is very troublesome to redefine a style. Therefore, if you have 1000 buttons and you want to set the color of each button to gold, you need to create 1000 objects to allocate each element separately. This makes the resources look huge.

In WPF, you can store styles, controls, animations, and even an object as a resource. However, each resource must be declared when the form is loaded. You can further allocate the resource to the control. You can maintain a global style in a separate resourcedictionary file. The style can be used by the whole application. Therefore, the WPF application is very container-applied to a topic.

New system attributes and binding capabilities

In the next step, I must introduce the new property system in WPF. Each WPF element defines a large number of dependency attributes. Dependency attributes are more powerful than common attributes. Therefore, the new attributes we define can easily register attributes for any object we want to register. Zhejiang Associates each object with the same observer. Because each element is inherited from dependencyobject, each element contains dependency observer. Once you register a variable as a dependency attribute, it creates a region on the observer to associate control with its value.

What is XAML?

According to definition, XAML is an XML-based life-marking language used to specify and set the features of classes. In other words, XAML is a language used by WPF, Silverlight, or other applications that can declare their own classes. Therefore, in your application, you can define variables for any class, define attributes, and use them directly. When rendering an application, the XAML parser automatically converts and creates the actual object.

XAML is usually used to define the UI layout in static and visualized aspects of elements and objects. We cannot use XAML to define program streams. Therefore, even with the powerful capability of XAML, it is not actually a programming language. It is used to design the UI for the application. Therefore, XAML uses C #, VB. NET, and other programming languages to define the code logic behind the scenes.

WPF Architecture

Every new technology requires a clear concept of its architecture. Therefore, before building your application, you must master several concepts. Skip this section if you do not like the details of WPF. As mentioned above, WPF is actually a set of assemblies that build the entire framework. These assemblies can be classified as follows:

Hosting Layer

Unmanaged Layer

Core APIs

Hosting layer: the hosting layer of WPF is built using some assembly. These assemblies build the WPF framework to communicate with the underlying unmanaged API to render its content. Some assembly components that constitute the WPF framework are:

Presentationframework. dll: Creates layout containers, controls, forms, and styles on the top layer.

Presentationcore. dll: It has basic types, such as uielement and visualization elements derived from all shapes and controls in presentationframework. dll.

Windowsbase. dll: they have more basic elements that can be used outside the WPF environment, such as dispatcher and dopendency. I will introduce them one by one later.

Unmanaged type (milcore. dll): the unmanaged layer in WPF is called milcore or the media consolidation library CORE. It basically processes the processing of higher-level WPF objects, such as layout containers, buttons, and animations, to meet direct3d expectations. It is the main rendering engine of WPF.

Windowscodecs. dll: a lower-level API supported by Image Processing in the WPF application. Windowscodecs. dll includes many encodings/decoders that convert images to vector images, which are then rendered to the screen.

Direct3d: This is a low-level API for WPF graphic rendering.

USER32: it is the main core API used by every program. It manages the separation of memory and processes.

GDI & Device Drivers: GDI and device drivers are unique to operating systems and are used to allow applications to access underlying APIs.

As discussed above, you can see what is the difference between elements of different frameworks for communication.

Several things you need to know before continuing exploration

Before you start building a WPF application, you must know a few things. What does dispatcher and thread affinity mean? When a WPF application is started, it automatically creates two threads at home. One is the rendering thread, which is hidden to the programmer. Therefore, you cannot directly use the rendering thread in your program. The other is the dispatcher thread, which actually contains all the UI elements. In other words, you may think that dispatcher is actually a UI thread, which restricts all the elements created in the WPF application. On the contrary, WPF requires that all the UI elements be associated with the dispather thread. This is the so-called thread Association. Therefore, you cannot change the elements created in the dispatcher thread in any other thread. It complies with the same restrictions of Win32 APIs. However, it allows you to use APIs to interoperate any WPF component as hwnd. Dispatcher is a class associated with processing threads. In fact, all elements are processed through the channel priority message loop. Each uielement is inherited from a dispatherobject that defines the dispatcher attribute. This dispather attribute points to the UI thread. Therefore, if you want to call or access the UI component from other threads, you need to call it through the dispatcher thread. Dispatcherobject has two main responsibilities: to check and confirm whether the object has the permission to access.
What is a visual tree and a logic tree?

Each encoding style contains different types of logic trees, thus forming the entire program. The logical tree contains the elements listed in XAML, so they only contain the controls you declare in XAML.

The visualization tree consists of components of a single control. You usually do not need to directly process the visualization tree. However, you should know how each control is made up, so using it will make it easier to build custom templates.

Before using it, you like to look at the visual tree. Expressionbuilder is a tool that can generate actual controls.

Why is there a routing event?

In C #, routedevent is quite new, but to those who come from JavaScript/Web technology, you may find it in your browser. There are actually two types of routedevent, one is to bubble to another element through the visualtree element, and the other is the element tunnel in the visualtree. Of course, there are also direct routing events that do not pass through the bubble and tunnel.

When a registered route event is called, it uses the visualized elements of the bubble/tunnel, and then calls all associated routedeventhandler registered one by one in the visualtree.

The distinction between the two, WPF uses this method to divide, preview ** as a tunnel routing event, ** as a bubble event. For example, ispreviewmousedown is a tunnel event in a visible element when the mouse is lifted. Therefore, when ispreviewmousedown is enabled, the element at the outermost layer is called first. When mousedown is enabled, the mousedown event of the innermost element is called.

Why dependencyobject?

Each WPF control is inherited from dependencyobject. Dependencyobject is a class that supports dependency attributes. The property system is created in WPF. Each object is inherited from dependencyobject, so it can be associated with various features that support the built-in WPF, such as eventtriggers, propertybindings, and animations.

Each dependyencyobject actually has an observer list. It declares three methods clearvalue, setvalue, and getvalue to add, edit, and delete these attributes. Therefore, when you use setvalue to store something, dependencyproperty will only create itself. This is also a way to save resources. We will also discuss dependencyproperty in detail in other articles.

What about hardware acceleration and graphic rendering in WPF?

Another important thing you should know is that you should know how WPF graphics are rendered. In fact, WPF rendering automatically detects how much hardware acceleration the current operating system supports and adjusts itself accordingly. Graphic rendering can detect appropriate layers for corresponding rendering output.

For hardware rendering, there are several major impacts:

1. video RAM: This determines the cache size and number of outputs used by the application to render. 2. pixel shader: this is an image tool used to process the acceleration effect on each pixel. 3. vertex shader: This is a graphic processing tool that performs mathematical calculations on the output vertex. They are also used to add special effects to objects in 3D environments. 4. multitexture blending: this is a special function that allows you to reference two or more textures on an object. Currently, the WPF rendering engine determines which layer is suitable for the current application and then applies the appropriate rendering layer tier 0: no hardware graphics acceleration occurs, and everything is rendered using software. Any version of direct 9 or earlier can present such output. Tier 1: Partial hardware and software rendering. You may use directx9 or a layer higher than this. Tier 2: Full Hardware acceleration. Directx9 or above can render the output. Object hierarchy

There are several objects in the WPF control. Let's discuss them one by one. (The abstract class is labeled with an elliptic, and the entity class is labeled with a rectangle)

Dispatcherobject: The base class of all WPF controls. Maintain dependencyobject in Ui thread: Build the observer visual of the dependency attribute: connect the observer library and milcoreuielement: Support for adding WPF features, such as layout, input, event, and so on. Frameworkelement: inherits from uielementshape: The base class control of all basic shapes: the UI object that interacts with users. Use the template to change its appearance contentcontrol: All base classes with a single content itemscontrol: The base class panel of all controls that display the set: the base classes of all containers, containers can prevent one or more controls from building your first WPF application.

Now it is time to create your first WPF application. To create a program, first open Visual Studio 2008/2010/2012/2013. In this example, Visual Studio 2008 is used to create a new project. You will see a new form. XAML should look like this:

<Window x:Class="FirstWindowsApplication.Window1"  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  x:Name="Window1"  Title="Window1" Height="300" Width="300">   <Grid>   </Grid></Window>

A blank window is generated here. Height/width indicates the size of the form. The title determines the text displayed on the title bar of the window. Each control in XAML should be named using the X: Name attribute and used to reference the window object in XAML. X: Class Attribute indicates the class associated with the current window. As I have told you, XAML is not self-sufficient. Therefore, you need to use C # Or VB. NET to define the specific logic.

Grid is a major layout object in the WPF application. Grid can have multiple child elements. Now let's put some controls in the grid.

<Grid>        <Grid.RowDefinitions>            <RowDefinition Height="Auto" />        </Grid.RowDefinitions>        <Grid.ColumnDefinitions>            <ColumnDefinition MinWidth="50" />            <ColumnDefinition Width="Auto" />            <ColumnDefinition Width="*" />        </Grid.ColumnDefinitions>        <TextBlock Text="Enter Name :" Grid.Row="0" Grid.Column="0" />        <TextBox x:Name="txtName" Grid.Row="0" Grid.Column="1" MinWidth="50"/>        <Button Content="Click Me" Grid.Row="0" Grid.Column="2" Click="Button_Click"/>    </Grid>

As you can see, I have defined a rowdefination and a columndefination. This will allow you to divide the grid into cells so that you can precisely place your controls where you want to place them. For each rowdefination and columndefination, you can use its width and height. You can see that I used 50, auto, and * as the width value. Auto indicates that the cell size will be defined when the control is defined. * Indicates that it occupies all the remaining controls. Therefore, you can see that the button occupies all the space left in this column.

Now, in the Post code, we have a MessageBox to display the textbox content.

private void Button_Click(object sender, RoutedEventArgs e) {     MessageBox.Show(string.Format("Hi {0}", this.txtName.Text)); }

So you can see that the system will prompt you for your name, isn't it interesting!

If you read this little XAML, you may be curious about how I can define this grid attribute in other controls. Just like defining grid. Row in each control. Using dependency properties makes this possible. This is a new feature introduced by WPF. We will discuss it in detail later.

Conclusion

This is the first part of the WPF series, including a preliminary discussion of the WPF application. I will go deep into other aspects of the WPF program, and how you use the WPF control to work and know that you are building a solution.

I hope you will like to read this article.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.