Table Of Contents - Programmer Books

Transcription

Table of ContentsMastering Windows Presentation FoundationCreditsAbout the AuthorAbout the Reviewerwww.PacktPub.comWhy subscribe?Customer FeedbackPrefaceWhat this book coversWhat you need for this bookWho this book is forConventionsReader feedbackCustomer supportDownloading the example codeDownloading the color images of this bookErrataPiracyQuestions1. A Smarter Way of Working with WPFWhat is MVVM and how does it help?ModelsView ModelsViewsData bindingSo how does MVVM help?Is there a downside?Debunking the myth about code behindLearning how to communicate againIntroducing the ICommand interfaceHandling events in Attached PropertiesMaking use of delegatesStructuring the application code baseSummary2. Debugging WPF ApplicationsUtilizing the Output windowPutting Presentation Trace Sources to workDiscovering inner exceptionsDebugging data bound values

Outputting values to UI controlsCatching changing Dependency Property valuesExploiting convertersSummary3. Writing Custom Application FrameworksWhat is an application framework?Encapsulating common functionalityIn base classesThrough interfacesWith Extension methodsIn UI controlsWith convertersConstructing a custom application frameworkSeparating the Data Access LayerProviding servicesImplementing Dependency InjectionConnecting Views with View ModelsSummary4. Becoming Proficient with Data BindingData binding basicsBinding path syntaxEscaping invalid charactersExploring the Binding classDirecting data bound trafficBinding to different sourcesBinding with priorityBinding from within control templatesBinding source changesConverting data bound valuesBinding multiple sources to a single target propertyDependency PropertiesSetting metadataDeclaring read-only Dependency PropertiesRegistering Attached PropertiesPrioritizing value setting sourcesData templatesTaking complete controlDisplaying hierarchical dataData binding to enumeration collectionsSummary5. Using the Right Controls for the JobInvestigating the built-in controlsInheriting framework abilities

Laying it on the lineContaining apPanelProviding custom layout behaviorContent controlsPresenting contentItems controlsAdornersModifying existing controlsStylingBeing resourcefulMerging resourcesTriggering changesTemplating controlsAttaching propertiesCombining controlsCreating custom controlsSummary6. Mastering Practical AnimationsInvestigating timelinesIntroducing key-framesTelling storiesControlling storyboardsEasing functionsAnimating along a pathCreating everyday animationsSummary7. Creating Visually Appealing User InterfacesStyling applications consistentlyOverriding default control stylesUsing professional iconsLayering visualsThrowing shadowsDeclaring multiple bordersReusing composite visualsReflecting lightCreating glowing effectsPutting it all together

Moving away from the ordinaryCasting reflectionsExploring borderless windowsVisualizing dataLivening up UI controlsSummary8. Implementing Responsive Data ValidationUsing validation rules - To do or not to do?Getting to grips with validation interfacesImplementing the IDataErrorInfo interfaceIntroducing the INotifyDataErrorInfo interfaceAnnotating dataVarying levels of validationIncorporating multiple validation techniquesCustomizing the error templateAvoiding UI-based validation errorsAmalgamating validation and visualsSummary9. Completing That Great User ExperienceProviding user feedbackUtilizing multiple threadsDiscovering the Async and Await keywordsBuilding asynchrony into our frameworkGoing the extra mileProducing in-application helpEnabling user preferencesExtending common courtesiesUn-burdening the end userSummary10. Improving Application PerformanceLeveraging the power of hardware renderingMaking more efficient resourcesFreezing objectsUsing the right controls for performanceDrawing conclusionsImaging more efficientlyEnhancing the performance of textual outputLiking the linkingData bindingRegistering Dependency PropertiesBinding to collectionsShrinking data objectsVirtualizing collections

Handling eventsSummary11. Deploying Your Masterpiece ApplicationInstalling Windows applicationsUtilizing ClickOnce functionalitySecuring deploymentsIsolating storageAccessing application versionsSummary12. What Next?Turning attention to future projectsImproving our application frameworkLogging errorsUsing online resources

Mastering Windows PresentationFoundation

Mastering Windows PresentationFoundationCopyright 2017 Packt PublishingAll rights reserved. No part of this book may be reproduced, stored in a retrieval system, ortransmitted in any form or by any means, without the prior written permission of thepublisher, except in the case of brief quotations embedded in critical articles or reviews.Every effort has been made in the preparation of this book to ensure the accuracy of theinformation presented. However, the information contained in this book is sold withoutwarranty, either express or implied. Neither the author, nor Packt Publishing, and its dealersand distributors will be held liable for any damages caused or alleged to be caused directlyor indirectly by this book.Packt Publishing has endeavored to provide trademark information about all of thecompanies and products mentioned in this book by the appropriate use of capitals.However, Packt Publishing cannot guarantee the accuracy of this information.First published: February 2017Production reference: 1130217Published by Packt Publishing Ltd.Livery Place35 Livery StreetBirminghamB3 2PB, UK.ISBN 978-1-78588-300-2www.packtpub.com

CreditsAuthorSheridan YuenCopy EditorPranjali ChuryReviewerAlex GoleshProject CoordinatorVaidehi SawantCommissioning EditorEdward GordonProofreaderSafis EditingAcquisition EditorChaitanya NairIndexerRekha NairContent Development EditorZeeyan PinheiroGraphicsKirk D'PenhaTechnical EditorKunal ChaudhariProduction CoordinatorShantanu N. Zagade

About the AuthorSheridan Yuen is a Microsoft .NET MCTS and Oracle Java SCJP certified softwaredeveloper, living in London, England. His passion for coding made him stand out from thecrowd right from the start. From his second year onward at university, he was employed tobe a teaching assistant for the first year student coding workshops and has since returnedas a guest lecturer.Among other prestigious positions, he was the primary software developer for the Ministryof Sound group for four years, working on their main music business application,responsible for creating their multi award winning albums. This application managed toincrease its users’ productivity by up to 80% in some cases.In addition to this, he architected a unique ticket scanning application for their award winningnightclub, making it the first club in the world to introduce scanned ticket entry across allstreams for their clients. Coming from a musical background and being a qualified audioengineer, with experience of record production and digital audio, this post was a perfectunion.He soon became a popular figure in the C# and WPF sections of the Stack Overflow,“question and answer” website, being awarded enough reputation by the communitymembers to raise him to well within the top half percent of all users. While authoring thisbook and other projects have kept him away for some time, he is keen to return to continueto help new users to get to grips with WPF.I would like to thank my long suffering girlfriend Jemma, who has regularly had to makedo without my company for the best part of a year, for her patience while I was composingand writing this book and the many examples in it. I’d also like to thank Chaitanya fromPackt Publishing for convincing me to write this book in the first place and without who,this book would not have been written.Finally, I would like to thank Mary Thomson, Professor Sarah Barman and ProfessorJames Orwell in particular, from Kingston University, London, who inspired me to changethe direction of my previous career and planted the seed of curiosity that has taken me sofar. I would also like to thank James for encouraging me to move from the Bachelor’sDegree course to the integrated Master’s Degree that I ended up gaining and for all of thebenefits that this brought with it.

About the ReviewerAlex Golesh is an international expert in XAML-based technologies such as UniversalWindows Platform (Windows, Windows Phone, HoloLens, Xbox One), Xamarin.Forms,WPF, and Silverlight. Also, Alex specializes in cloud-based solutions such as MicrosoftAzure. Alex developed training solutions for Microsoft Learning on Windows Phone andWindows 8 and delivers workshops for developers and enterprises. Alex leads thearchitecture and development process in multiple projects for his clients.

www.PacktPub.comFor support files and downloads related to your book, please visit www.PacktPub.com.Did you know that Packt offers eBook versions of every book published, with PDF andePub files available? You can upgrade to the eBook version at www.PacktPub.com and asa print book customer, you are entitled to a discount on the eBook copy. Get in touch withus at service@packtpub.com for more details.At www.PacktPub.com, you can also read a collection of free technical articles, sign up fora range of free newsletters and receive exclusive discounts and offers on Packt books andeBooks.https://www.packtpub.com/maptGet the most in-demand software skills with Mapt. Mapt gives you full access to all Packtbooks and video courses, as well as industry-leading tools to help you plan your personaldevelopment and advance your career.Why subscribe?Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Customer FeedbackThanks for purchasing this Packt book. At Packt, quality is at the heart of our editorialprocess. To help us improve, please leave us an honest review on this book's Amazon pageat https://goo.gl/yuUApD.If you'd like to join our team of regular reviewers, you can email us atcustomerreviews@packtpub.com. We award our regular reviewers with free eBooks andvideos in exchange for their valuable feedback. Help us be relentless in improving ourproducts!

PrefaceWhile it can be easy to construct a basic form using WPF, it takes a lot more to fullyunderstand what WPF can do for us and how best to use it. It has a steep learning curveand it can be difficult to comprehend this very different way of working. This book aims tohelp you to get over that initial hill and continue to fully enable you to implement any givenrequirement.This book will start by providing you the foundation knowledge on how to improve yourworkflow and what to do when you have problems. It will build upon this foundation byintroducing the base layer of the application that will serve all that comes after it. We willthen take a detour to cover data binding in detail.The book will then turn to the User Interface (UI) and how to get the most out of the built-inand custom WPF controls. It will make clear which customization methods are best to utilizein a wide range of scenarios, avoiding the need to rewrite existing functionality. Other tipsand tricks will also be provided to enable you to create your own visually stunning UIs.The final section of the book will introduce the concluding ways for you to polish yourapplications, from adding practical animations and data validation, to improving applicationperformance. The book will end by explaining how to deploy the applications that you havebeen working so hard on and discuss other things that you can now achieve with your newfound knowledge.

What this book coversChapter 1, A Smarter Way of Working with WPF, introduces the Model, View, View Model(MVVM) software architectural pattern and the benefits of using it with WPF.Chapter 2, Debugging WPF Applications, provides essential tips on various methods ofdebugging WPF applications, ensuring the ability to iron out any problems that may occur.Chapter 3, Writing Custom Application Frameworks, introduces the indispensable conceptof application frameworks, with early examples that will be built upon as the bookprogresses. By the end of the book, you will have a fully functioning Framework with whichto build your applications upon.Chapter 4, Becoming Proficient with Data Binding, demystifies data binding and clearlydemonstrates how to use it in a practical application. A plethora of examples will help you tounderstand which binding syntax to use in any given situation and to be confident that theirbindings will work as expected.Chapter 5, Using The Right Controls for The Job, explains which controls to use inparticular situations and describes the various ways to modify them when required. Itclearly outlines how to customize existing controls and how to create custom controls whenrequired.Chapter 6, Mastering Practical Animations, explains the ins and outs of WPF Animations,detailing lesser known functionality. It concludes with a number of ideas for practicalanimations and continues to build upon the custom application framework.Chapter 7, Creating Visually Stunning User Interfaces, offers advice for getting the mostout of the WPF visuals, while remaining practical, and provides handy tips on makingapplications stand out from the crowd.Chapter 8, Implementing Responsive Data Validation, presents a number of methods ofdata validation to suit every situation and continues to build upon the custom applicationframework. It covers full, partial, instant, and delayed validation and a variety of differentways to display validation errors.Chapter 9, Completing That Great User Experience, provides tips for creating applicationswith a great user experience. Concepts introduced here, such as asynchronous dataaccess and keeping the end users well informed, will substantially improve the existingcustom application framework.Chapter 10, Improving Application Performance, lists a number of ways to increase theperformance of WPF applications from freezing resources to implementing virtualization.Readers that follow these tips and tricks can rest assured that their WPF applications willperform as optimally as they can.Chapter 11, Deploying Your Masterpiece Application, covers the final requirement for allprofessional applications—deployment. It includes the older method of using the WindowsInstaller software, along with the more common and up-to-date method of using ClickOncefunctionality.Chapter 12, What Next?, summarizes what you have learned from this book and suggestswhat you can do with many of your various new skills. It provides you with further ideas onextending the application framework.

What you need for this bookAs with all WPF development, you'll need to have the .NET Framework and a version ofMicrosoft's Visual Studio integrated development environment software installed on yourcomputer.You'll be able to use versions as old as 2010, but in order to use the code in the book thattakes advantage of the latest .NET Framework improvements, you'll need to use one of thenewer versions. Note that any edition of Visual Studio can be used, from the top of the lineEnterprise edition to the free Community (2015) edition.

Who this book is forThis book is for working developers with a basic to moderate level of knowledge aboutWindows Presentation Foundation and for those interested in improving their practical dayto day WPF skills. It will also be of special interest to individuals wanting to know moreabout application architecture and those wanting to improve the look of their userinterfaces.

ConventionsIn this book, you will find a number of text styles that distinguish between different kinds ofinformation. Here are some examples of these styles and an explanation of their meaning.Code words in text, database table names, folder names, filenames, file extensions,pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "There aretwo other useful properties declared by the Grid class."A block of code is set as follows:public string Name{get { return name; }set{if (name ! value){name value;NotifyPropertyChanged("Name");}}}Any command-line input or output is written as follows:System.Windows.Data Error: 17 : Cannot get 'Item[]' value (type'ValidationError') from '(Validation.Errors)' (type'ReadOnlyObservableCollection 1').BindingExpression:Path (Validation.Errors)[0].ErrorContent;DataItem 'TextBox' (Name ''); target element is 'TextBox'(Name '');target property is 'ToolTip' (type entOutOfRangeException:Specified argument was out of the range of valid values.New terms and important words are shown in bold. Words that you see on the screen,for example, in menus or dialog boxes, appear in the text like this: "The Cancel button hasbeen declared in the second row and column."NoteWarnings or important notes appear in a box like this.TipTips and tricks appear like this.

Reader feedbackFeedback from our readers is always welcome. Let us know what you think about thisbook-what you liked or disliked. Reader feedback is important for us as it helps us developtitles that you will really get the most out of. To send us general feedback, simply email feedback@packtpub.com, and mention the book's title in the subject of your message. Ifthere is a topic that you have expertise in and you are interested in either writing orcontributing to a book, see our author guide at www.packtpub.com/authors.

Customer supportNow that you are the proud owner of a Packt book, we have a number of things to help youto get the most from your purchase.Downloading the example codeYou can download the example code files for this book from your account athttp://www.packtpub.com. If you purchased this book elsewhere, you can visithttp://www.packtpub.com/support and register to have the files e-mailed directly to you.You can download the code files by following these steps:1. Log in or register to our website using your e-mail address and password.2. Hover the mouse pointer on the SUPPORT tab at the top.3. Click on Code Downloads & Errata.4. Enter the name of the book in the Search box.5. Select the book for which you're looking to download the code files.6. Choose from the drop-down menu where you purchased this book from.7. Click on Code Download.Once the file is downloaded, please make sure that you unzip or extract the folder using thelatest version of:WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for LinuxThe code bundle for the book is also hosted on GitHub dows-Presentation-Foundation. We alsohave other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!Downloading the color images of this bookWe also provide you with a PDF file that has color images of the screenshots/diagramsused in this book. The color images will help you better understand the changes in theoutput. You can download this file hough we have taken every care to ensure the accuracy of our content, mistakes dohappen. If you find a mistake in one of our books-maybe a mistake in the text or the codewe would be grateful if you could report this to us. By doing so, you can save other readersfrom frustration and help us improve subsequent versions of this book. If you find anyerrata, please report them by visiting http://www.packtpub.com/submit-errata, selectingyour book, clicking on the Errata Submission Form link, and entering the details of yourerrata. Once your errata are verified, your submission will be accepted and the errata willbe uploaded to our website or added to any list of existing errata under the Errata sectionof that title.To view the previously submitted errata, go to

https://www.packtpub.com/books/content/support and enter the name of the book in thesearch field. The required information will appear under the Errata section.PiracyPiracy of copyrighted material on the Internet is an ongoing problem across all media. AtPackt, we take the protection of our copyright and licenses very seriously. If you comeacross any illegal copies of our works in any form on the Internet, please provide us withthe location address or website name immediately so that we can pursue a remedy.Please contact us at copyright@packtpub.com with a link to the suspected pirated material.We appreciate your help in protecting our authors and our ability to bring you valuablecontent.QuestionsIf you have a problem with any aspect of this book, you can contact usat questions@packtpub.com, and we will do our best to address the problem.

Chapter 1. A Smarter Way of Working withWPFWhen Windows Presentation Foundation (WPF) was first released as part of the .NETFramework version 3.0 in 2006, it was billed as the future of desktop application GraphicalUser Interface (GUI) languages and supporters claimed that it would put an end to theprevious GUI technology, Windows Forms. However, as time passed, it has fallen far shortof this claim.There are three main reasons that WPF has not taken off as widely as previously expected.The first reason has nothing to do with WPF and stems from the recent push to hosteverything in the cloud and having web interfaces rather than desktop applications. Thesecond reason relates to the very steep learning curve and the very different way ofworking that is required to master WPF.The last reason is that it is not a very efficient language and if a WPF application has lots of'bells and whistles' in, then either the client computers will need to have additional RAMand/or graphics cards installed, or they could face a slow and stuttering user experience.This explains why many companies that make use of WPF today are in the finance industry,where they can afford to upgrade all users' computers to be able to run their applicationsoptimally. This book will aim to make WPF more accessible to the rest of us by providingpractical tips and tricks to help build our real-world applications more easily and moreefficiently.One of the simplest changes with the biggest workflow improvements that we can make toimprove the way we work with WPF is to follow the MVVM software architectural pattern. Itdescribes how we can organize our classes to make our applications more maintainable,testable, and generally simpler to understand. In this chapter, we will take a closer look atthis pattern and discover how it can help us to improve our applications.After discovering what MVVM is and what its benefits are, we'll learn several new ways tocommunicate between the various components in this new environment. We'll then focus onthe physical structure of the code base in a typical MVVM application and investigate avariety of alternative arrangements.What is MVVM and how does it help?Model-View-View Model (MVVM) is a software architectural pattern that was famouslyintroduced by John Gossman on his blog back in 2005 and is now commonly used whendeveloping WPF applications. Its main purpose is to provide a Separation of Concernsbetween the business model, the User Interface (UI), and the business logic. It does thisby dividing them into three distinct types of core components: Models, Views, and ViewModels. Let's take a look at how they are arranged and what each of these componentsrepresent.

As we can see here, the View Models component sits between the Models and the Viewsand provides two-way access to each of them. It should be noted at this point that thereshould be no direct relationship between the Views and Models components and only looseconnections between the other components. Let's now take a closer look at what each ofthese components represent.ModelsUnlike the other MVVM components, the Model constituent comprises of a number ofelements. It encompasses the business data model along with its related validation logicand also the Data Access Layer (DAL), or data repositories, that provide the applicationwith data access and persistence.The data model represents the classes that hold the data in the application. They typicallymirror the columns in the database more or less, although it is common that they arehierarchical in form, and so may require joins to be performed in the data source in order tofully populate them. One alternative would be to design the data model classes to fit therequirements in the UI, but either way, the business logic or validation rules will typicallyreside in the same project as the data model.The code that is used to interface with whatever data persistence technology is used in ourapplication is also included within the Models component of the pattern. Care should betaken when it comes to organizing this component in the code base, as there are a numberof issues to take into consideration. We'll investigate this further in a while, but for now, let'scontinue to find out more about the components in this pattern.View ModelsThe View Models can be explained easily; each View Model provides its associated Viewwith all of the data and functionality that it requires. In some ways, they can be consideredto be similar to the old Windows Forms code behind files, except that they have no directrelationship with the View that they are serving. A better analogy, if you're familiar withMVC, would be that they are similar to the Controllers in the Model-View-Controller (MVC)software architectural pattern. In fact, in his blog, John describes the MVVM pattern asbeing a variation of the MVC pattern.They have two-way connections with the Model component in order to access and updatethe data that the Views require, and often, they transform that data in some way to make iteasier to display and interact with in the UI. They also have two-way connections with theViews through data binding and property change notification. In short, View Models formthe bridge between the Model and the View, which otherwise have no connection to each

other.However, it should be noted that the View Models are only loosely connected to the Viewsand Model components through their data binding and interfaces. The beauty of this patternenables each element to be able to function independently from each other.To maintain the separation between the View Models and the View, we avoid declaring anyproperties of UI-related types in the View Model. We don't want any references to UIrelated DLLs in our View Models project, and so we make use of custom IValueConverterimplementations to convert them to primitive types. For example, we might convertVisibility objects from the UI to plain bool values or convert the selection of somecolored Brush objects to an Enum instance that is safe to use in the View Model.ViewsThe Views define the appearance and layout of the UI. They typically connect with a ViewModel through the use of their DataContext property and display the data that it supplies.They expose the functionality provided by the View Model by connecting its commands tothe UI controls that the users interact with.In general, the basic rule of thumb is that each View has one associated View Model. Thisdoes not mean that a View cannot data bind to more than one data source or that wecannot reuse View Models. It simply means that, in general, if we have a class calledSecurityView, it is more than likely that we'll also have an instance of a class namedSecurityViewModel that will be set as the value of that View's DataContext property.Data bindingOne often overlooked aspect of the MVVM pattern is its requirement for data binding. Wecould not have the full Separation of Concerns without it, as there would be no easy way ofcommunicating between the Views and View Models. The XAML markup, data bindingclasses, and ICommand and INotifyPropertyChanged interfaces are the main tools in WPFthat provide this functionality.The ICommand interface is how commanding is implemented in the .NET Framework. Itprovides behavior that implements and even extends the ever useful Command pattern, inwhich an object encapsulates everything needed to perform an action. Most of the UIcontrols in WPF have Command properties that we can use to connect them to thefunctionality that the commands provide.The INotifyPropertyChanged interface is used to notify binding clients that property valueshave been changed. For example, if we had a User object and it had a Name property, thenour User class would be responsible for raising the PropertyChanged event of theINotifyPropertyChanged interface, specifying the name of the property each time its valuewas changed. We'll look much deeper into all of this later, but now let's see how thearrangement of these components help us.So how does MVVM help?One major benefit of adopting MVVM is that it provides the crucial Separation of Concernsbetween the business model, the UI, and the business logic. This enables us to do severalthings. It frees the View Models from the Models, both the business model and the data

persistence technology. This in turn enables us to reuse the business model in otherapplications and swap out the DAL and replace it with a mock data layer so that we caneffectively test the functionality in our view models without requiring any kind of real dataconnection.It also disconnects the Views from the View logic that they require, as this is provided bythe View Models. This allows us to run each component independently, which has theadvantage of enabling one team to work on designing the Views, while another team workson the View Models. Having parallel work streams enables companies to benefit from vastlyreduced production times.Furthermore, this separation also makes it easier for us to swap the Views for a differenttechnology without needing to change our Model code. We may well need to change som

Windows Platform (Windows, Windows Phone, HoloLens, Xbox One), Xamarin.Forms, WPF, and Silverlight. Also, Alex specializes in cloud-based solutions such as Microsoft Azure. Alex developed training solutions for Microsoft Learning on Windows Phone and Windows 8 and delivers workshops for developers and enterprises. Alex leads the