Location>code7788 >text

CH01_WPF Overview

Popularity:336 ℃/2024-08-15 15:35:36

Chapter 1: WPF Overview

Objectives of the chapter

  • Understanding Windows Graphics Evolution
  • Understanding the WPF Advanced API
  • Understanding the concept of resolution independence
  • Understanding the WPF Architecture
  • Understanding WPF 4.5

WPF Overview

Welcome to the Windows Presentation Foundation (WPF) Desktop Guide, a resolution-independent UI framework using a vector-based rendering engine built to take advantage of modern graphics hardware. WPF provides a comprehensive set of application development capabilities that include Extensible Application Markup Language (XAML), controls, data binding, layout, 2D and 3D graphics, animation, styles, templates, documents, media, text, and layout. WPF belongs to .NET, so it is possible to generate applications that integrate other elements of the .NET API.

Windows Graphics Evolution

For nearly 15 years prior to the introduction of WPF, Windows developers had been using essentially the same display technology. The reason for this is that every system Windows application prior to that relied on the following two time-honored parts of the Windows operating system to create its user interface:

  • User32: This section provides a familiar Windows look to many elements such as windows, buttons and text boxes.
  • GDI/GDI+: This section provides drawing support for rendering simple shapes, text, and images, but adds complexity (and often poor performance).

DirectX: New Graphics Engine

Microsoft had provided a solution to the limitations of the User32 and GDVGDi+ libraries: DireaXk. Direstk started out as an error-prone, combinatorial toolkit for developing games on the Windows platform. directX was designed with a focus on speed, and for this reason. Microsof worked closely with graphics card vendors to provide DirectX with the hardware acceleration needed for complex texture mapping, special effects such as translucency, and three-dimensional graphics.

DirectX has matured over the years since it was first released (shortly after Windows 95). DirectX is now a fundamental part of Windows, supporting all modern graphics cards. However, the DirectX programming API has remained true to its original design and is still used primarily as a toolkit for game developers. Because of its inherent complexity, DirectX is almost never used to develop traditional types of Windows applications such as business software.

WPF completely reverses this situation. In WPF, the underlying graphics technology is no longer GDIGDI+, but Diresdk, and in fact, no matter what kind of user interface is created, WPF applications use DirectX at the bottom of the hierarchy, which means that whether you're designing a complex 3D graphic, which is DirectX's specialty, or just drawing a few buttons and plain text, all of the drawing work is done through the DirectX pipeline. As a result, rich effects such as translucency and antialiasing are available to even the most common commercial applications. There are also benefits in terms of hardware acceleration, as DirectX does as much of the work in rendering graphics as possible to the graphics processing unit (GPU), which is a processor dedicated to the graphics card.

Attention:

Dircaix is more efficient because it understands high-level elements that can be rendered directly by the graphics card, such as textures and gradients.
GDIGDI+, on the other hand, does not understand these high-level elements and therefore must convert them into pixel-by-pixel instructions, which are even slower to render via modern graphics cards.

However, one User32 component remains, which is used only to a limited extent. This is because WPF still relies on User32 for specific services, such as processing and routing input and distinguishing which application actually owns which part of the screen. However, all drawing operations are done by DirectX.

Hardware Acceleration and WPF

Graphics cards are different in terms of their support for specific sorority dye features and optimizations. Thankfully, this is not a problem for two reasons. First, most computers today are equipped with graphics hardware that is sufficient to support WPF features such as 3D drawing and animation.
This is true even for laptops and desktop computers with integrated graphics processors (graphics processors integrated into the motherboard, not a separate card). Second, WPF prepares software processing for all the work to be done. This means that WPB is intelligent enough to try to use hardware optimizations, but it can also use software calculations to do the same work if necessary. So, if you run a WPF application on a computer with an old graphics card, the interface will still display the way it was designed to. Of course, software calculations are naturally much slower, and computers with older graphics cards do not run rich WPF applications very smoothly. This is especially true if the rich WPF application contains complex animations or other intensive graphical effects.

What is WPF

WPF (Windows Presentation Foundation) is a desktop application framework developed by Microsoft for creating modern, highly interactive and visually appealing user interfaces. It is part of the .NET Framework and provides a declarative programming model based on the XAML (Extensible Application Markup Language) language that makes it easy to create dynamic, flexible user interfaces and seamlessly integrates with other .NET technologies. NET technologies. WPF also features powerful data binding and reusability, allowing developers to build and maintain applications faster, and supports hardware acceleration and high-resolution displays for a better user experience.

Differences between WPF and Winform

WPF (Windows Presentation Foundation) and WinForms (Windows Forms) are both frameworks for creating Windows desktop applications, but they have some important differences:

  1. Programming Model: WPF is a declarative programming model based on XAML, which makes it easy to create dynamic and flexible user interfaces with support for animations and advanced visual effects. WinForms, on the other hand, is based on the traditional imperative programming model, where you need to manually set the properties and event handlers of each control in the code.
  2. Data Binding: WPF has a powerful data binding system that can bind UI elements and data sources to each other, making it easier for applications to manage and update data.WinForms also supports data binding, but it is not as flexible as WPF.
  3. Reusability: WPF supports styles and templates so that UI elements can be easily reused and customized, which greatly simplifies application development and maintenance, while WinForms requires each UI element to be created manually, which is less easy to reuse.
  4. Vector graphics and resolution: WPF uses vector graphics that render sharp images on high-resolution screens, whereas WinForms uses pixel graphics that may appear blurry or distorted on high-resolution screens.

WPF : Advanced API

If WPF only offered hardware acceleration through DireclX, it would be an important improvement, not a revolutionary change. In fact, WPF includes a whole set of advanced services for application programmers.

The following is a list of some of the most important changes introduced by WPF to the Windows programming landscape.

Web-like layout model

Instead of fixing controls in specific locations with specific coordinates, WPF focuses on a flexible flow layout, arranging controls flexibly according to their content so that the user interface adapts to widely varying content and different languages.

Rich Drawing Models

Instead of drawing pixel by pixel, you can work directly with elements in WPF - basic shapes, text blocks, and other graphical elements. Other new features such as truly transparent controls, the ability to place multiple layers of content with different levels of transparency, and native 3D support are also available.

Rich Text Modeling

WPF provides Windows applications with the ability to display richly styled text anywhere in the user interface. Text can even be combined with lists, floating graphics, and other user interface elements. And if you need to display large amounts of text, you can use advanced document display features such as line breaks, separations, and alignment to improve readability!

Animation as a primary programming concept

In WPF, there is no need for a timer to force a window to redraw itself. Instead, animations are an inherent part of the WPF framework. Animations can be defined in WPF using declarative tags, and WPF will make them move automatically.

Support for audio and video media

Previous user interface development toolkits (such as Windows Forms) had significant limitations in handling multimedia. However, WPF supports the playback of audio and video files supported by any Windows media player and allows multiple media files to be played simultaneously. Even more strikingly, WPF provides tools that allow the integration of video content in other parts of the user interface, as well as allowing the addition of special effects tricks, such as placing a video window on a rotating 3D cube.

Styles and Templates

Styles allow for standardization of the display format and can be used repeatedly throughout the application.
With templates it is possible to change the way elements are rendered and even the way core controls such as buttons are rendered. It has never been easier to create modern user interfaces with skins.

command

Most users have come to realize that triggering an Open command from a menu or toolbar makes no difference, the end result is the same. Now with code abstraction, application commands can be defined in specific locations and linked to multiple controls.

declarative user interface (DUI)

Although you can write code to create WPF windows, Visual Studio provides another way. It serializes the contents of each window into a set of XML. tags in a XAML document. The advantage is that the user interface is completely separate from the code, and graphic designers have access to specialized tools for editing the XANL file and ultimately touching up the front-end interface of the application.XAML stands for Extensible Application Markup Language, which is covered in detail in Chapter 2. XAML stands for Extensible Application Markup Language.

Page-based applications

WPF can be used to create browser-like applications that move through a set of pages with "forward" and "backward" navigation buttons. WPF takes care of the messy details, such as page history. You can even deploy your project as a browser-based application that runs in the real world.

resolution independence

Traditionally, Windows applications have been limited by specific assumed screen resolutions. When designing windows, developers usually assume a standard monitor resolution (e.g., 1366×768 pixels) and try to ensure that the window can be reasonably resized for smaller or larger resolutions.

The problem is that the user interface of traditional Windows applications is not scalable. As a result, if you use a higher resolution monitor, the pixels will be more closely spaced and the application window will become smaller and harder to read. Especially with newer displays that use more closely spaced pixels, the problem is exacerbated when running at higher resolutions. For example, it is common to find users using a number of monitors (especially those on portable computers) that have a pixel alignment density of 120 dpi (dot per inch) or 144 dpi, which is more than the more common 96 dpi. When these monitors use their default resolution, the pixels are displayed in a much tighter pattern, making controls and text smaller.

It is logical that applications should use a higher pixel density to display more detail. For example, a high resolution monitor can display the same size toolbar icon, but use more pixels to display a sharper graphic. This maintains the same basic layout, but increases clarity and detail. This solution has not been possible in the past for a number of reasons. Although it is possible to change the size of the content of graphics drawn with CDIGDi+, User32 (which is responsible for generating the visual appearance of common controls) does not support true scaling.

This problem no longer exists in WPF because WPF renders all user interface elements by itself, from simple shapes to common controls like buttons. So if you create a 1-inch-wide button on a computer monitor, it will still be 1 inch wide on a higher-resolution monitor - WPF just renders the button in more detail using more pixels.

A general description is given here and explained with a few details. The most important thing to realize is that the WPE scales according to the system DPI setting, and does not scale according to the DPI of the physical display device. This makes perfect sense - after all, when displaying an application on a 100-inch projector, you may be standing a few steps behind the projector and want to see the extra-large version of the window. You don't want WPF to suddenly shrink the application to "normal" size. Similarly, if you're using a portable computer with a higher resolution monitor, you may want a slightly smaller window - that's the price you have to pay for displaying information on a smaller screen. Further, different users have different preferences. Some users may want to display more detail, while others may want to display more content.

So how does WPF determine the size of an application window? Simply put, it uses the system DPI setting when WPF calculates the window size. But to understand the underlying workings, it's helpful to explore the WPF metrics system further.

WPF Units

WPF windows and all elements within them are measured using device-independent units. A device-independent unit is defined as 1/96 of an inch. To understand what this means in practice, an example will be analyzed below.

Imagine creating a small button with dimensions of 96x96 units using WPF. If you use the standard Windows DPT setting (96 dp), each device-independent unit actually corresponds to one physical pixel. Because for this case, WPF uses the following formula:

Physical unit size] = [Device-independent unit size] × [System DP]

= 1/96 inch X 96 dpi
= 1 pixel

Essentially, WPF assumes that 96 pixels are used to make up 1 inch, as this is what the Windows operating system tells WPF via the system DPI setting. But it actually depends on the display device.

System DPI

So far, the WPF button example is exactly the same as any other arbitrary user interface element in any other type of Windows application. If you change the system DPI setting, the result is different. In previous generations of Windows, this feature was sometimes referred to as large fonts. This is because back then the system DPI affected the size of the system fonts, but other details usually remained the same.

Attention:

Many Windows applications do not fully support higher DPI settings. In the worst case scenario, increasing the system DPI may cause some content in the window to be scaled but other content to be unscaled, which may result in some content being hidden or even the window being unusable.

This is where WPF differs, as WPF itself supports system DPI settings very easily. For example, setting the system
The DPI setting is changed to 120 dpi (often chosen by users of high-resolution monitors), and WPF assumes that 120 pixels are needed to fill the
1 inch of space.WPF uses the following formula to calculate how to transform logical units into physical device pixels:

[Physical unit size] = [Device-independent unit size] × [System DPI]

= 1/96 in. x 120 dpi
= 1.25 pixels

In other words, with the system DPI set to 120 dpi, the WPF rendering engine assumes that the device-independent unit is equal to 1.25 pixels.
If a 96 x 96 pixel sized button is displayed, the physical size is actually 120 x 120 pixels (since 96 x 1.25 = 120).
This is exactly the result you'd expect - buttons that are 1" in size on a standard monitor remain 1" in size on a monitor with a higher pixel density.

If used only for buttons, this auto-scaling wouldn't make much sense. But WPF uses device-independent units for anything it displays, including shapes, controls, text, and other content placed in the window. So the system DPI can be changed to any desired value and WPF will seamlessly resize the application.

Attention:

Pixel sizes calculated based on system DPI may be trivial. It can be assumed that WPF simply scales the metric size to the nearest pixel. However, by default, WPF handles this differently. If an edge of an element falls between two pixels, WPF will use the antialiasing feature to blend the edge to the neighboring pixel. This may seem like a redundant choice, but it does improve the visual effect. If you add a skinning effect to a control and use a custom-drawn graphic, the edges may not be neatly and clearly defined, thus requiring some degree of antialiasing.

Bitmap and vector graphics

When using normal controls, it is natural to take advantage of the resolution independence of WTPF, which takes care of making sure that any displayed content is automatically sized correctly. However, problems can occasionally arise when preparing to include images in an application. For example, in traditional Windows applications, developers use very small bitmaps for toolbar command buttons, but this is not an ideal approach in WPF applications because bitmaps can suffer from artifacts (become blurred) when scaled up or down according to the system DPI. Instead, when designing a WPF user interface, even the smallest icons are usually implemented using vector graphics. Vector graphics are defined as a series of shapes and they can be easily scaled to any size.

Attention:

Of course, it takes longer to draw a vector graphic than it does to draw a basic bitmap, but WPF includes optimizations that reduce overhead to ensure that performance is always within reason.

The importance of resolution independence cannot be overemphasized. Because at first glance, it looks like a simple, graceful solution to this time-honored problem (which it is). But in order to design fully scalable user interfaces, developers need to embrace a new mindset.

WPF Architecture

WPF uses a multi-tier architecture. At the top level, the application interacts with a set of high-level constraints written entirely in managed C* code. The actual work of converting .NET objects to Direct3D textures and triangles is done in the background by a low-level unmanaged component called . It is implemented using unmanaged code because it is tightly integrated with Direct3D and it is extremely performance sensitive.

The following figure shows how the layers work in a WPF application:

Listed below are some of the important components included in the diagram above:

Contains the top-level types of WPF, including those that represent windows, panels, and other types of controls. It also implements high-level programming abstractions such as styles. Most of the classes used directly by developers come from this assembly.

Contains base types such as the UIElement class and the Visual class, from which all shape and control classes inherit. If you don't need all the features of the window and control abstraction layer, you can use this layer and still take advantage of WPF's rendering engine.

contains more basic elements that have the potential for reuse outside of WPF, such as the DispatcherObject class and the DependencyObject class, which introduce the dependency property (see Chapter 4 for details).

It is the core of the WPF dyeing system and the foundation of the Media Integration Layer (MIL). Its compositing engine transforms visual elements into the triangles and textures expected by Direct3D. Although considered part of WPF, it is also one of the core system components of Windows Vista and Windows 7. In fact, the Desktop Window Manager (DWM) uses it to render the desktop.

is a set of low-level APIs that provide image support (such as processing, displaying, and scaling bitmap and JPEG images).
• Direct3D

is a set of low-level APIs from which all graphics in a WPF application are rendered.
• User32

is used to determine which programs actually occupy which part of the desktop. So it's still included in WPF, but it's no longer responsible for rendering generic controls.

class hierarchy

The following figure briefly shows several important branches in the class hierarchy.

The following will briefly describe the core classes presented in the diagram above, many of which make up the complete branch of elements (e.g., shapes, panels, and controls).

Attention:

WPF core namespaces begin with (e.g. , and ). The only exceptions are namespaces starting with , which are part of the Windows Forms Toolkit.

, class
WPF applications use the well-known Single-ThreadAmipity (STA) model, which means that the entire user interface is owned by a single thread. It is not safe to interact with user interface elements from another thread. To facilitate the use of this model, each WPF application is managed by a dispatcher that coordinates messages (keyboard input, mouse movements, and even frame processing such as layout). By inheriting from the DispatcherOljoot class, each element in the user interface can check to see if the code is running on the correct thread, and can send code to the user interface thread through the inter-visit scheduler.

resemble
In WPF, the main way to interact with elements on the original screen is through properties. In the early design stages, the WPF designers decided to create a more robust property model that would support many features such as change notification, inheritance of recognized values, and a smaller footprint. The end result was the dependency properp property, which is analyzed in Chapter 4.
Support for dependency properties is available to WPF classes by inheriting from the DependencyObject class.

resemble
Every element displayed in a WPF window is essentially a Visual object. Think of Visuals as drawing objects that encapsulate drawing instructions, additional details about how to perform the drawing (such as cropping, transparency, and transform settings), and basic functionality (such as hit testing.) Visual classes also provide a link between managed WPF libraries and the Fairy Desktop's assembly. Any class that inherits from Visual can be displayed on the window. If you prefer to create user interfaces using lightweight APIs rather than using the advanced framework features of WPF.

  1. resemble
    The UIElement class adds support for WPF intrinsic features such as layout, input, focus, and events (the WPF team uses the acronym LIFE for this). For example, a two-step process of measuring and arranging layouts is defined here, which will be covered in Chapter 18. In this class, primitive mouse clicks and key presses are converted into more useful events, such as the MouseEnter event. Similar to properties, WPF implements an enhanced event routing system called routed event.

. .
The FrameworkElement class is the last stop in the WPF core inheritance tree. This class implements a number of members that are all defined by the UIElement class. For example, the UIElement class sets the foundation for the WPF layout system, but the FrameworkElement class provides important properties to support it (such as the HorizontalAlignment and Margin properties.) The UIElement class also adds support for core features such as quantity binding, animation, and styles.

resemble
Basic shape classes (such as Rectangle, Polygon, Ellipse, Line, and Path) inherit from this class.
These shape classes can be used in conjunction with more traditional Windows widgets such as buttons and text cabinets.

  1. resemble

Controls are meta-projects that can be interacted with by the user. Controls obviously include TextBox, Button, and ListBox classes, etc. The Contol class provides additional properties for setting fonts and foreground and background colors. But the most interesting detail is the template support, which allows you to replace the standard appearance of a control with a custom-style drawing. Control templates are described in Chapter 17.

Attention:

In Windows Forms programming, each visual item in a form is called a control; in WPF, this is no longer the case.
Visual content is called a clerent, and only some elements are controls (controls are elements that receive focus and can interact with the user). More confusingly, many elements are defined in namespaces, but they are not inherited from classes and are not considered controls.

resemble
The ContentControl class is the base class for all controls with a single piece of content, ranging from a simple label to the entire contents of a window. The most impressive part of the model is that the single content of a control can be anything from a plain string to a layout panel with a combination of other shapes and controls.

resemble
The ItemsControl class is the base class for all controls that display collections of options, such as ListBox and TreeView controls. List controls are very flexible - for example, using the built-in features of the ItemsControl class, a simple ListBox control can be transformed into a list of radio buttons, a list of checkbox controls, a tiled image, or a combination of completely different elements of your choice. In fact, menus, toolbars, and status bars in WPF are all specific lists, and the classes that implement them all inherit from the ItemsContorl class.
resemble
The Panel class is the base class for all layout containers, which are elements that can contain one or more child elements and arrange them according to specific rules. These containers are the foundation of the WPF layout system, and their use is key to arranging content in the most attractive and flexible way possible.

WPF 4.5

WPF is a mature technology. It is part of several released .NET platforms and is constantly being refined through the following two releases:

-NET Framewordk 3.0. This is the first version of WPF to be released along with two other new technologies: WCF (Windows Communication Foundation) and Windows WF (Workflow Foundation). These three new technologies are collectively known as .NET Framewordk 3.0.

- WPF 3.5.One year later, a new version of WPF was released as part of . The new features in this new version of WPF are mainly minor improvements, including bug fixes and performance improvements.
- WPF 3.5 SP1. When the .NET Framework Service Pack 1 (SP1) was released, WPF designers jumped at the chance to add new features such as smooth graphical effects (implemented through pixel shaders) and an advanced DataGrid control.
-WPF4. This version of WPF has a lot of improvements, including better rendering of text, more natural and smooth animations, and support for multi-touch.
- WPF 4.5. Compared to the above updates, this latest WPF release has the fewest updates to WPE 4 so far, which is a sign of the maturity of WPF technology. In addition to correcting some general bugs and making performance adjustments, WPF 4.5 also makes a number of improvements to the data binding system, such as improving data binding expressions, visualization, and the ability to support the INotifyDataBror interface and data view synchronization.

First WPF program

1. New projects

2. Writing code

3. Run the program

Summary of the chapter

This chapter provides a brief introduction to WPF and its role, analyzes the underlying architecture of WPF, and briefly describes the core classes.
Obviously, WPF introduces many important changes. However, there are five important guidelines that stand out more because they are so different from previous Windows user interface toolkits such as Windows Forms. These guidelines are listed below:

Hardware acceleration.

Perform all WPF drawing operations through DirectX to take advantage of the latest features of modern graphics cards.

Resolution independence.

WPF has the flexibility to zoom in and out of the display based on the system DPI settings to make it fit the monitor and display options used.

The control has no fixed appearance.

In traditional Windows development, there is a big difference between customized on-demand controls, which are self-drawing controls, and controls rendered by the operating system that are essentially fixed in appearance. In WPF, everything from a basic Rectangle shape to a standard Button control or a more complex Toolbar control is drawn using the same rendering engine and is fully customizable. For this reason, WPF controls are often referred to as appearanceless controls - they define the functionality of the control, but do not have a fixed "look".

Declarative User Interfaces.

Chapter 2 introduces XAML, the markup standard for defining WPF user interfaces. With XANL, windows can be created without having to write code. In particular, the power of XAML is not limited to creating static user interfaces. Many tools such as data binding and triggers can be used to automate basic user interface behavior (e.g., textboxes updating themselves when the page passes through a record source, labels highlighting when the mouse moves over them), all without writing C# code.

Object-based mapping.

Even if you are prepared to work on a lower level visualization layer (rather than a higher level element layer), you don't need to work with drawings and pixels, but rather create graphical objects and have WPF display them as optimally as possible.

homework after school

not have