1. 首页
  2. 编程语言
  3. C#
  4. Pro WPF 4.5 in C#(第四版)

Pro WPF 4.5 in C#(第四版)

上传者: 2018-12-28 13:14:03上传 PDF文件 13.89MB 热度 111次
■ About the author■ About the technical reviewer.n……iAcknowledgments.mmmeemmammmeammammemaamemamaaaneamaaaemma XXViiiIntroduction……111311313XPart: Fundamentals…Chapter 1: Introducing WPF mARRRAABARBRRBARBARARBAREIDChapter2:XAML…,,,,,,,,,,,,,,,,,,21Chapter3: Layout…,,,,,,.,.,..,,,,,53Chapter 4: Dependency Properties mtmaamaaamnamamamanaamamnmamaamnaaamaam. 93Chapter5: Routed events…,,,,,,,,,,,,………105Part ll: Deeper Into WPF141Chapter 6: Controls.a3Chapter 7: The application man,195Chapter8: Element Binding…,,…,,,…,,,…,,,,,,,,,,227Chapter 9: Commands243Chapter 10: Resources mmmaaameammamamamnamamaaeamamamaamanmaaamnmaa 269Chapter 11: Styles and Behaviors .anaaaaasaasaasaasaasaasaasaasaaamasaaamaaan 283Part lll: Drawing and Animation305Chapter 12: Shapes, Brushes, and Transforms307Chapter 13: Geometries and Drawings.aman347Chapter 14: Effects and visuals amamnaaaaaaaaaaaaaaann 369Chapter 15: Animation Basics.mmmamamamammmnamaamaaamanmaanmaamanamamm. 391■ CONTENTS AT A GLANCEChapter 16: Advanced Animation431Part IV: Templates and custom Elements463Chapter 17: Control Templates.mmmmmemmannoeeaa amendment. 465Chapter18; Custom elements….,.,,,,,,,,,,,…,…,…,,505Part va datan555Chapter 19: Data Binding7Chapter 20: Formatting bound datan601Chapter 21: Data Views…647Chapter 22: Lists, Trees, and Grids665Part v: Windows, Pages, and Rich controls705Chapter23: Windows…,,,,,,,,,,,,,,,,707Chapter 24: Pages and Navigation amamamnmamamnmammnmmm741Chapter 25: Menus, Toolbars, and Ribbons787Chapter 26: Sound and videon.813Chapter 27: 3-D Drawingn837Part VI: Documents and Printing.am.n881Chapter 28: Documents mmmmmmmmmmammaaaasammmmmmmm 883Chapter29: Printing….,.,...,,,,,,,,935Part VIll: Additional Topics…965Chapter 30: Interacting with Windows Forms..967Chapter 31: Multithreading983Chapter 32: The Add-in Modeln97Chapter 33: ClickOnce Deploymentn1021Indexn…11041The Windows Presentation Foundation(WPF) is a modern graphical display system for Windows. It's aradical change from the technologies that came before it, with innovative features such as built-inhardware acceleration and resolution independence, both of which you'll explore in this chapterWPF is the best toolkit to use if you want to build a rich desktop application that runs on WindowsVista, Windows 7, and Windows 8 in desktop mode (as well as the corresponding versions of windowsServer). In fact, it's the only general-purpose toolkit that targets these versions of windows. By comparisonMicrosoft's new Metro toolkit--although exciting-is limited to Windows 8 systems only.(WPFapplications can even be made to run on ancient Windows XP computers, which are still found in manybusinesses. The only limitation is that you must configure Visual Studio to target the slightly older. NET 4.0Framework, rather than. NET 4.5In this chapter, you'll take your first look at the architecture of WPE. You'll learn how it deals withvarying screen resolutions, and you'll get a high-level survey of its core assemblies and classes. You' ll alsoconsider how wpf has evolved from its initial release to version 4.5The Evolution of Windows GraphicsThat's because every traditional, pre-WPF Windows application relies on two well-worn parts of theBefore WPE Windows developers spent nearly 15 years using essentially the same display technologWindows operating system to create its user interfaceUser 32: This provides the traditional Windows look and feel for elements such aswindows, buttons, text boxes, and so onGDI/GDI+: This provides drawing support for rendering shapes, text, and images atthe cost of additional complexity(and often lackluster performance)Over the years, both technologies have been refined, and the aPis that developers use to interact withthem have changed dramatically. But whether you're crafting an application with. NET and WindowsForms or even Visual Basic 6 or MFC-based C++ code, behind the scenes the same parts of the Windowsoperating system are at work. Different frameworks simply provide different wrappers for interacting withUser32 and GDI/GDI+. They can provide improvements in efficiency, reduce complexity, and addprebaked features so you don t have to code them yourself; but they cant remove the fundamentallimitations of a system component that was designed more than a decade agoDownloadathttp://www.pin5i.comCHAPTER 1 INTRODUCING WPFNote The basic division of labor between User32 and GDI/GDI+ was introduced more than 15 years ago andtablished in Windows 3.0. Of course, User 32 was simply User at that point, because software hadn't yetentered the 32-bit worldDirectX: The New graphics EngineMicrosoft created one way around the limitations of the User 32 and gDI/gDI+ libraries: DirectX. DirectXbegan as a cobbled-together, error-prone toolkit for creating games on the Windows platform. Its designmandate was speed, and so Microsoft worked closely with video card vendors to give DirectX the hardwareacceleration needed for complex textures, special effects such as partial transparency, and threedimensional graphicsOver the years since it was first introduced (shortly after Windows 95), DirectX has matured It's nowan integral part of windows, with support for all modern video cards. However, the programming API forDirectX still reflects its roots as a game developer's toolkit Because of its raw complexity, DirectX is almostnever used in traditional types of Windows applications(such as business software)In fact, WPF applications use DirectX no matter what type of user interface you create. That means thar t.WPF changes all this In WPE, the underlying graphics technology isnt GDI/GDI+. Instead, it's Direcwhether you're designing complex three-dimensional graphics(DirectX's forte)or just drawing buttonsand plain text all the drawing work travels through the DirectX pipeline. as a result, even the mostmundane business applications can use rich effects such as transparency and anti-aliasing. You alsobenefit from hardware acceleration, which simply means DirectX hands off as much work as possible tothe graphics processing unit (GPU), which is the dedicated processor on the video card.Note Directx is more efficient because it understands higher-level ingredients such as textures and gradientsthat can be rendered directly by the video card. GDI/GDI doesn't, so it needs to convert them to pixel-by-pixelinstructions, which are rendered much more slowly by modern video cardsOne component that's still in the picture (to a limited extent) is User32. That's because WPF still relieswhich portion of screen real estate. However, all the drawing is funneled through Direct tapplication ownson User32 for certain services, such as handling and routing input and sorting out whichHardware Acceleration and wpFVideo cards differ in their support for specialized rendering features and optimizations. Fortunately, thisisnt a problem, for two reasons. First, most modern computers have video hardware that's more thanpowerful enough for WPF features such as 3-D drawing and animation. This is true even of laptops anddesktop computers with integrated graphics (graphics processors that are built in to the motherboard,rather than on a separate card). Second, WPF has a software fallback for everything it does. That meansWPF is intelligent enough to use hardware optimizations where possible, but can perform the same workusing software calculations if necessary. So if you run a WPF application on a computer with a legacy videocard, the interface will still appear the way you designed it. Of course, the software alternative may bemuch slower, so you'll find that computers with older video cards wont run rich WPF applications verywell, especially ones that incorporate complex animations or other intense graphical effectsDownloadathttp://www.pin5i.comCHAPTER 1 INTRODUCING WPFWPF: A Higher-Level APlIf the only thing WPF offered was hardware acceleration through DirectX, it would be a compellingimprovement but a limited one. But WPF includes a basket of high-level services designed for applicationprogrammers.The following are some of the most dramatic changes that WPF ushers into the Windowsprogramming worldA web-like layout model: Rather than fix controls in place with specific coordinates,WPF emphasizes flexible flow layout that arranges controls based on their contentThe result is a user interface that can adapt to show highly dynamic content ordifferent languagesA rich drawing model: Rather than painting pixels, in WPF you deal with primitivesbasic shapes, blocks of text, and other graphical ingredients. You also have newfeatures, such as true transparent controls, the ability to stack multiple layers withdifferent opacities, and native 3-D supportArich text model: WPF gives Windows applications the ability to display rich, styledtext anywhere in a user interface. You can even combine text with lists, floatingfigures, and other user interface elements. And if you need to display large amountsof text, you can use advanced document display features such as wrappingcolumns, and justification to improve readability.Animation as a first-class programming concept: In WPE there's no need to use atimer to force a form to repaint itself. Instead, animation is an intrinsic part of theframework You define animations with declarative tags, and WPF puts them intoaction automatically.Support for audio and video media: Previous user interface toolkits, such asWindows Forms, were surprisingly limited when dealing with multimedia. But WPFincludes support for playing any audio or video file supported by Windows MediaPlayer, and it allows you to play more than one media file at once. Even moreimpressively, it gives you the tools to integrate video content into the rest of youruser interface, allowing you to pull off exotic tricks such as placing a video windowon a spinning 3-D cubeStyles and templates: Styles allow you to standardize formatting and reuse itthroughout your application Templates allow you to change the way any element isrendered, even a core control such as the button it has never been easier to buildmodern skinned interfacesCommands: Most users realize that it doesnt matter whether they trigger the Opencommand through a menu or through a toolbar; the end result is the same. Now thatabstraction is available to your code, you can define an application command in oneplace and link it to multiple controlsDeclarative user interface: Although you can construct a WPF window with codeVisual Studio takes a different approach It serializes each windows content to a setof XMl tags in a XAML document. The advantage is that your user interface iscompletely separated from your code, and graphic designers can use professionaltools to edit your XaMl files and refine your applications front end (XAML is shortfor Extensible Application Markup Language, and it's described in detail inChapter 2.Downloadathttp://www.pin5i.com5CHAPTER 1 INTRODUCING WPFlets you move through a collection of pages, complete with forward and backPage-based applications: Using WPF, you can build a browser-like application thnavigation buttons. WPF handles the messy details such as the page history. You caneven deploy your project as a browser-based application that runs right insideInternet Explorer.resolution IndependenceTraditional Windows applications are bound by certain assumptions about resolution. Developers usuallyassume a standard monitor resolution( such as 1366 x 768 pixels), design their windows with that in mind,and try to ensure reasonable resizing behavior for smaller and larger dimensionsThe problem is that the user interface in traditional windows applications isnt scalable. As a result, ifyou use a high monitor resolution that crams in pixels more densely, your application windows becomesmaller and more difficult to read. This is particularly a problem with newer monitors that have high pixeldensities and run at correspondingly high resolutions. For example, it's common to find consumermonitors(particularly on laptops) that have pixel densities of 120 dpi or 144 dpi (dots per inch), ratherthan the more traditional 96 dpi. At their native resolution, these displays pack the pixels in much moretightly, creating eye-squintingly small controls and textIdeally, applications would use higher pixel densities to show more detail. For example, a highresolution monitor could display similarly sized toolbar icons but use the extra pixels to render sharpergraphics. That way, you could keep the same basic layout but offer increased clarity and detail. For avariety of reasons, this solution hasnt been possible in the past. Although you can resize graphical contentthat's drawn with GDI/GDI+, User32(which generates the visuals for common controls) doesnt supporttrue scalingWPF doesnt suffer from this problem because it renders all user interface elements itself, from simpleshapes to common controls such as buttons. As a result, if you create a button that's l inch wide on yourcomputer monitor, it can remain 1 inch wide on a high-resolution monitor--WPF will simply render it ingreater detail and with more pixelsThis is the big picture, but it glosses over a few details. Most importantly, you need to realize that WPFbases its scaling on the system DPI setting, not the DPI of your physical display device. This makes perfectsense--after all, if you're displaying your application on a 100-inch projector, you're probably standingseveral feet back and expecting to see a jumbo-size version of your windows. You dont want WPF tosuddenly scale down your application to"normal"size. Similarly, if you're using a laptop with a highresolution display, you probably expect to have slightly smaller windows-it's the price you pay to fit allyour information onto a smaller screen. Furthermore, different users have different preferences. Somewant richer detail, while others prefer to cram in more contentSo, how does wpf determine how big an application window should be The short answer is that WPFuses the system DPI setting when it calculates sizes. But to understand how this really works, it helps totake a closer look at the wPF measurement systemWPF UnitsA WPF window and all the elements inside it are measured using device-independent units. A single deviceindependent unit is defined as 1/96 of an inch. To understand what this means in practice, you'll need toconsider an exampleImagine that you create a small button in WPf that's 96 by 96 units in size. If you're using the standardWindows dpi setting(96 dpi), each device-independent unit corresponds to one real, physical pixel. That'sbecause wpF uses this calculation6Downloadathttp://www.pin5i.comCHAPTER 1 INTRODUCING WPF[Physical Unit Size]= [Device-Independent Unit Size] x [System DPI1/96 inch x 96 dpipiXeEssentially, WPF assumes it takes 96 pixels to make an inch because Windows tells it that through thesystem DPI setting. However, the reality depends on your display deviceFor example, consider a 19-inch LCD monitor with a maximum resolution of 1600 by 1200 pixelsUsing a dash of Pythagoras, you can calculate the pixel density for this monitor, as shown hereScreen DPn= y60%+ 12002 Pixels9 inches100 dpiIn this case, the pixel density works out to 100 dpi, which is slightly higher than what Windowsassumes. As a result, on this monitor a 96-by-96-pixel button will be slightly smaller than l inch.On the other hand, consider a 15-inch LCD monitor with a resolution of 1024 by 768. Here, the pixeldensity drops to about 85 dpi, so the 96-by-96-pixel button appears slightly larger than l inchIn both these cases, if you reduce the screen size(say, by switching to 800 by 600 resolution), thebutton (and every other screen element) will appear proportionately larger. That's because the system DPIsetting remains at 96 dpi. In other words, Windows continues to assume it takes 96 pixels to make an inch,even though at a lower resolution it takes far fewer pixelsTip As you no doubt know, LCD monitors are designed to work best at a specific resolution, which is called thenative resolution. If you lower the resolution, the monitor must use interpolation to fill in the extra pixels, which cancause blurriness. To get the best display, it's always best to use the native resolution If you want larger windowsbuttons, and text, consider modifying the system DPI setting instead (as described next)ystem DPISo far, the WPF button example works exactly the same as any other user interface element in any othertype of Windows application. The difference is the result if you change the system DPI setting. In theprevious generation of Windows, this feature was sometimes called large fonts. That's because the systemDPI affects the system font size but often leaves other details unchangedNote Many Windows applications don't fully support higher dPl settings. At worst, increasing the system DPlcan result in windows that have some content that' s scaled up and other content that isn't, which can lead toobscured content and even unusable windowsThis is where WPF is different. WPF respects the system DPI setting natively and effortlessly. Forexample, if you change the system DPI setting to 120 dpi(a common choice for users of large highresolution screens), WPF assumes that it needs 120 pixels to fill an inch of space. WPF uses the followingcalculation to figure out how it should translate its logical units to physical device pixelsDownloadathttp://www.pin5i.com
用户评论