47,99 €
Gain comprehensive insight into WPF mechanics and capabilities.
Windows Presentation Foundation (WPF) is Microsoft's development tool for building rich Windows client user experiences that incorporate UIs, media, and documents. With the updates in .NET 4.7, Visual Studio 2017, C# 7, and .NET Standard 2.0, WPF has taken giant strides and is now easier than ever for developers to use.
If you want to get an in-depth view of WPF mechanics and capabilities, then this
book is for you.
The book begins by teaching you about the fundamentals of WPF and then quickly shows you the standard controls and the layout options. It teaches you about data bindings and how to utilize resources and the MVVM pattern to maintain a clean and reusable structure in your code. After this, you will explore the animation capabilities of WPF and see how they integrate with other mechanisms. Towards the end of the book, you will learn about WCF services and explore WPF's support for debugging and asynchronous operations.
By the end of the book, you will have a deep understanding of WPF and will know how to build resilient applications.
The book is intended for developers who are relatively new to WPF (Windows Presentation Foundation), or those who have been working with WPF for some time, but want to get a deeper understanding of its foundation and concepts to gain practical knowledge. Basic knowledge of C# and Visual Studio is assumed.
Kunal Chowdhury has been a Microsoft MVP since 2010. He is a renowned public speaker, an active blogger (by passion), and a software engineer (technical lead) by profession. Over the years, he has acquired profound knowledge of various Microsoft products and helped developers throughout the world with his deep knowledge and experience. He has authored the book Mastering Visual Studio 2017 and written many articles, tips, and tricks on his technical blog (kunal-chowdhury [DOT] com) for developers and consumers. You can follow him on Twitter at @kunal2383 and become one of his fans on social media.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 429
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, 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 the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Merint MathewAcquisition Editor: Nitin DasanContent Development Editor: Akshada IyerTechnical Editor: Supriya ThabeCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Jisha ChirayilProduction Coordinator: Shantanu Zagade
First published: February 2018
Production reference: 1210218
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78839-980-7
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Kunal Chowdhury has been a Microsoft MVP since 2010. He is a renowned public speaker, an active blogger (by passion), and a software engineer (technical lead) by profession. Over the years, he has acquired profound knowledge of various Microsoft products and helped developers throughout the world with his deep knowledge and experience.
He has authored the book Mastering Visual Studio 2017 and written many articles, tips, and tricks on his technical blog (kunal-chowdhury [DOT] com) for developers and consumers. You can follow him on Twitter at @kunal2383 and become one of his fans on social media.
Alvin Ashcraft is a developer living near Philadelphia. He has spent his 23-year career building software with C#, Visual Studio, WPF, ASP.NET, and more. He has been awarded, nine times, a Microsoft MVP. You can read his daily links for .NET developers on his blog, the Morning Dew. He works as a principal software engineer for Allscripts, building healthcare software. He has previously been employed with software companies, including Oracle. He has reviewed titles for Packt Publishing, such as Mastering ASP.NET Core 2.0, Mastering Entity Framework Core 2.0, and Learning ASP.NET Core 2.0.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Windows Presentation Foundation Development Cookbook
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Download the color images
Conventions used
Get in touch
Reviews
WPF Fundamentals
Introduction
The WPF Architecture
Presentation Framework
Presentation Core
Common Language Runtime
Media Integration Library
OS Core
Types of WPF applications
The XAML overview
XAML syntax terminologies
Object element syntax
Property Attribute syntax
Property Element syntax
Content syntax
Collection syntax
Event Attribute syntax
Installing WPF Workload with Visual Studio 2017
Getting ready
How to do it...
Creating WPF applications
Getting ready
How to do it...
There's more...
Creating and navigating from one window to another
Getting ready
How to do it...
How it works...
There's more...
Creating and navigating from one page to another
Getting ready
How to do it...
How it works...
There's more...
Creating a dialog box
Getting ready
How to do it...
How it works...
There's more...
Using the open file dialog
Using the save file dialog
Using the print dialog
Other common dialogs
Creating ownership between windows
Getting ready
How to do it...
How it works...
There's more...
Creating a single instance application
Getting ready
How to do it...
How it works...
There's more...
Passing arguments to WPF applications
Getting ready
How to do it...
How it works...
There's more...
Handling unhandled exceptions
Getting ready
How to do it...
How it works...
There's more...
Using WPF Standard Controls
Introduction
Using the TextBlock control to add plain text
Getting ready
How to do it...
How it works...
There's more...
Using Label to add other controls in text
Getting ready
How to do it...
How it works...
There's more...
Providing a user option to input text
Getting ready
How to do it...
How it works...
There's more...
Windows Clipboard support
Adding spellcheck support
Adding images to your application UI
Getting ready
How to do it...
How it works...
There's more...
Working with ready-to-use 2D shapes
Getting ready
How to do it...
How it works...
There's more...
Adding tooltips to show additional information
Getting ready
How to do it...
How it works...
There's more...
Adding a standard menu to the WPF application
Getting ready
How to do it...
How it works...
There's more...
Adding an access key to menus
Adding icons to menus
Adding checkable menu items
Adding click-event handlers to menus
Providing extra functionalities using the context menu
Getting ready
How to do it...
How it works...
Adding user options with radio buttons and checkboxes
Getting ready
How to do it...
How it works...
There's more...
Working with the progress bar control
Getting ready
How to do it...
How it works...
Using the Slider control to pick a numeric value
Getting ready
How to do it...
How it works...
There's more...
Using the Calendar control in your application
Getting ready
How to do it...
How it works...
There's more...
The SelectionModes property
The DisplayDate property
The DisplayMode property
The BlackoutDates property
Listing items in a Listbox control
Getting ready
How to do it...
How it works...
There's more...
Implementing multi selection
Customizing the ListBoxItem with multiple controls
Providing options to select from a ComboBox
Getting ready
How to do it...
How it works...
There's more...
Adding a status bar to your window
Getting ready
How to do it...
How it works...
Adding a toolbar panel to perform quick tasks
Getting ready
How to do it...
How it works...
Layouts and Panels
Introduction
Building a UI layout using a Grid
Getting ready
How to do it...
How it works...
There's more...
Creating a resizable Grid
Spanning elements across multiple rows and/or columns
Placing elements in uniform cells
Getting ready
How to do it...
How it works...
There's more...
Setting the row and column count
Defining the first cell of the UniformGrid
Filling elements from right to left
Automatically repositioning controls using WrapPanel
Getting ready
How to do it...
How it works...
There's more...
Placing controls in a Stack
Getting ready
How to do it...
How it works...
There's more...
Positioning controls inside a Canvas
Getting ready
How to do it...
How it works...
There's more...
Wrapping UI elements using a Border
Getting ready
How to do it...
How it works...
Creating a scrollable panel
Getting ready
How to do it...
How it works...
Docking controls using the DockPanel
Getting ready
How to do it...
How it works...
There's more...
Rescaling UI elements using a ViewBox
Getting ready
How to do it...
How it works...
There's more...
Creating a tabbed layout
Getting ready
How to do it...
How it works...
Dynamically adding/removing elements in a panel
Getting ready
How to do it...
How it works...
There's more...
Implementing the drag and drop feature
Getting ready
How to do it...
How it works...
There's more...
Working with Data Bindings
Introduction
Working with CLR properties and UI notifications
Getting ready
How to do it...
How it works...
There's more...
Working with dependency properties
Getting ready
How to do it...
How it works...
There's more...
Working with attached properties
Getting ready
How to do it...
How it works...
Data binding to an object
Getting ready
How to do it...
How it works...
Data binding to a collection
Getting ready
How to do it...
How it works...
There's more...
Element-to-element data binding
Getting ready
How to do it...
How it works...
Sorting data in a DataGrid control
Getting ready
How to do it...
How it works...
Grouping data in a DataGrid control
Getting ready
How to do it...
How it works...
There's more...
Filtering data in a DataGrid control
Getting ready
How to do it...
How it works...
Using static bindings
Getting ready
How to do it...
How it works...
Using value converters
Getting ready
How to do it...
How it works...
There's more...
Using multi-value converters
Getting ready
How to do it...
How it works...
Using Custom Controls and User Controls
Introduction
Creating a custom control
Getting ready
How to do it...
How it works...
There's more...
XMLNS attribute declaration
Default styling
Toolbox integration
Customizing the template of a custom control
Getting ready
How to do it...
How it works...
Exposing properties from the custom control
Getting ready
How to do it...
How it works...
Exposing events from a custom control
Getting ready
How to do it...
How it works...
Extending the functionality of a control using behavior
Getting ready
How to do it...
How it works...
Creating a User Control interface
Getting ready
How to do it...
How it works...
Exposing events from a User Control
Getting ready
How to do it...
How it works...
Customizing the XMLNS namespace
Getting ready
How to do it...
How it works...
Using Styles, Templates, and Triggers
Introduction
Creating the style of a control
Getting ready
How to do it...
How it works...
There's more...
Creating the Style of a control based on another Style
Getting ready
How to do it...
How it works...
Applying Style to a control automatically
Getting ready
How to do it...
How it works...
Editing the template of any control
Getting ready
How to do it...
How it works...
There's more...
Creating a property trigger
Getting ready
How to do it...
How it works...
Creating a multi trigger
Getting ready
How to do it...
How it works...
Creating a data trigger
Getting ready
How to do it...
How it works...
Creating a multi data trigger
Getting ready
How to do it...
How it works...
Creating an event trigger
Getting ready
How to do it...
How it works...
Using Resources and MVVM Patterns
Introduction
Using binary resources inside a WPF application
Getting ready
How to do it...
How it works...
There's more...
Using binary resources from another assembly
Getting ready
How to do it...
How it works...
There's more...
Accessing binary resources in code
Getting ready
How to do it...
How it works...
Using static logical resources in WPF
Getting ready
How to do it...
How it works...
There's more...
Using dynamic logical resources in WPF
Getting ready
How to do it...
How it works...
There's more...
Managing logical resources
Getting ready
How to do it...
How it works...
There's more...
Using user selected colors and fonts
Getting ready
How to do it...
How it works...
There's more...
Building an application using the MVVM pattern
Getting ready
How to do it...
How it works...
Using routed commands in a WPF application
Getting ready
How to do it...
How it works...
Working with Animations
Introduction
Scaling an element while rendering
Getting ready
How to do it...
How it works...
Rotating an element while rendering
Getting ready
How to do it...
How it works...
Skewing an element while rendering
Getting ready
How to do it...
How it works...
Moving an element while rendering
Getting ready
How to do it...
How it works...
Grouping multiple transforms
Getting ready
How to do it...
How it works...
There's more...
Creating property-based animations
Getting ready
How to do it...
How it works...
Creating path-based animations
Getting ready
How to do it...
How it works...
Creating key-frame-based animations
Getting ready
How to do it...
How it works...
There's more...
Adding easing effects to animations
Getting ready
How to do it...
How it works...
There's more...
BounceEase
CircleEase
CubicEase
ElasticEase
ExponentialEase
PowerEase
QuadraticEase
QuarticEase
QuinticEase
SineEase
Using WCF Services
Introduction
Creating a WCF service
Getting ready
How to do it...
How it works...
The DataContract attribute
The DataMember attribute
The ServiceContract attribute
The OperationContract attribute
Self-hosting a WCF service
Getting ready
How to do it...
How it works...
There's more...
Hosting a WCF service in an IIS server
Getting ready
How to do it...
How it works...
Integrating a WCF service in a WPF application
Getting ready
How to do it...
How it works...
There's more...
Debugging and Threading
Introduction
Enabling the UI debugging tool for XAML
Getting ready
How to do it...
Navigating through XAML elements using Live Visual Tree
Getting ready
How to do it...
How it works...
There's more...
Inspecting XAML properties using Live Property Explorer
Getting ready
How to do it...
How it works...
There's more...
Updating the UI from a non-UI thread
Getting ready
How to do it...
How it works...
There's more...
Adding cancelation support to long running threads
Getting ready
How to do it...
How it works...
Using the background worker component
Getting ready
How to do it...
How it works...
There's more...
Using a timer to periodically update the UI
Getting ready
How to do it...
How it works...
Interoperability with Win32 and WinForm
Introduction
Hosting WinForm controls in WPF applications
Getting ready
How to do it...
How it works...
There's more...
Hosting WPF controls in WinForm applications
Getting ready
How to do it...
How it works...
Calling Win32 APIs from WPF applications
Getting ready
How to do it...
How it works...
Embedding ActiveX controls in WPF applications
Getting ready
How to do it...
How it works...
Other Books You May Enjoy
Leave a review - let other readers know what you think
Along with Windows 1.0, in the year 1985, Microsoft introduced Graphics Device Interface (GDI) and the USER subsystem in order to build a Windows-based Graphical User Interface (GUI). In 1990, OpenGL came into picture to create 2D and 3D graphics on Windows and non-Windows systems. In 1995, Microsoft presented another technology, called DirectX, to create high-performance 2D/3D graphics. Later, GDI+ was introduced to add alpha blending and gradient brush support on top of the existing GDI.
In 2002, Microsoft introduced .NET Framework. Along with this, Windows Forms was also introduced to build User Interface (UI) for Windows using C# and Visual Basic languages. It was built on top of GDI+, and hence, it still had the limitations of the GDI+ and USER subsystems.
Over the years, Microsoft decided to bring a new technology to build rich UIs for Windows-based applications, which not only helped the users (developers and designers) to escape the limitations of GDI/GDI+ and USER subsystems, but also helped them to improve their productivity when building desktop-based applications.
In November 2006, along with .NET 3.0, Windows Presentation Foundation (WPF) was introduced to provide the developers a unified programming model to build dynamic, data-driven desktop applications for Windows. It came with a broad set of features to create a graphical subsystem to render rich UIs using various controls, layouts, graphics, resources, and more, considering the application and the security of the data. As it was first shipped as part of the .NET Framework 3.0, the first release was called WPF 3.0.
WPF is a resolution-independent framework that uses a vector-based rendering engine using an XML-based language called XAML (pronounced Zammel), to create modern user experiences that provided a declarative model for application programming. Using this, you can easily customize the controls and add skins to it to get a better representation of the application's UI.
As WPF was different than classic Windows Forms, as it uses XAML, data binding, templates, styles, animations, documents, and more, initially it got little attention. However, later, it started gaining a lot of popularity and attraction. Many updated versions were released to add more functionality to it to make it robust and powerful.
In this book, we will cover a set of recipes that will show you how to perform common tasks using WPF. Starting with WPF fundamentals, we will cover standard controls, layouts, panels, data bindings, custom controls, user controls, styles, templates, triggers, and animations and later move on to the uses of resources, MVVM patterns, WCF services, debugging, threading, and WPF interoperabilities, to make sure you understand the foundation properly.
The examples given in this book are simple, easy to understand, and provide you with a what you need to learn and master the skills that you need to build desktop applications using WPF. By the time you reach the end of this book, you will be proficient enough with deep knowledge about each of the chapters that it covers. Although this book has covered most of the important topics, there will always be some topics that no books can completely cover. You will definitely enjoy reading this book, as there are lots of graphical and textual steps to help you gain confidence working with Windows Presentation Foundation.
The book is intended for developers who are relatively new to Windows Presentation Foundation (WPF) or those who have been working with WPF for some time, but want to get a deeper understanding of its foundation and concepts to gain practical knowledge. Basic knowledge of C# and Visual Studio is assumed.
Chapter 1, WPF Fundamentals, focuses on WPF's architecture, application types, and XAML syntax, terminologies, and explains how to install WPF Workload with Visual Studio 2017 to create your first application targeting Windows Presentation Foundation. It will cover the navigation mechanisms, various dialog boxes, building ownership between multiple windows, and then proceed toward creating a single instance application. This chapter will then cover how to pass arguments to WPF application and how to handle unhandled exceptions thrown in WPF.
Chapter 2, Using WPF Standard Controls, provides you with an in-depth knowledge to help you learn about various common control parts of WPF. This chapter will begin with TextBlock, Label, TextBox, and Image controls, and then continue with 2D shapes, Tooltip, standard menu, Context Menu, Radio buttons, and CheckBox controls. This chapter will also cover how to work with Progress Bar, Slider, Calendar, ListBox, ComboBox, StatusBar, and Toolbar panel.
Chapter 3, Layouts and Panels, gives you quick tour of the standard layout and panels. This chapter will cover how to use the panels to create proper layouts. It will also cover implementing the drag and drop feature in brief.
Chapter 4, Working with Data Bindings, discusses the important concept of data binding and how to use it in WPF. It also discusses CLR properties, dependency properties, attached properties, converters, and data operations (such as sorting, grouping, and filtering). The step-by-step approaches will guide you to be proficient with all types of data bindings.
Chapter 5, Using Custom Controls and User Controls, provides the basic building blocks you need to create custom controls and user controls that you can reuse in various places. You will also learn how to customize the control template using custom properties and events from the custom controls and user controls.
Chapter 6, Using Styles, Templates, and Triggers, provides a deep insight into the styles and templates of a control, followed by various triggers that you can use to perform some operations or UI changes directly from the XAML, without using any C# code.
Chapter 7, Using Resources and MVVM Patterns, begins by demonstrating various ways to use and manage binary resources, logical resources, and static resources. It will then continue with the Model View ViewModel (MVVM) pattern to build a WPF application by writing less code in the code behind file. The MVVM pattern is introduced with some examples to show how you can build command bindings.
Chapter 8, Working with Animations, provides a tour to the animation capabilities in WPF and discusses how to use various transforms and animations and apply effects to animations.
Chapter 9, Using WCF Services, makes it easy for you to understand the ABC of WCF services and explains how to create, host, and consume them in a WPF application.
Chapter 10, Debugging and Threading, discusses WPF's support for debugging the XAML application UI using the Live Visual Tree and Live Property Explorer. This chapter helps you to create asynchronous operations so that the application UI is always responsive.
Chapter 11, Interoperability with Win32 and WinForm, focuses on understanding the interoperability of WPF with Win32 and Windows Forms. In this chapter, you will learn how to host an element from one technology (WPF/WinForm) to other technology (WinForm/WPF), followed by calling Win32 APIs and embedding ActiveX controls in a WPF application.
This book assumes that the reader has knowledge of .NET Framework and C# (at least C# version 3.0, but C# 7.0 or higher version is preferable) and has working experience of Visual Studio 2015 or higher (Visual Studio 2017 is preferable). Basic knowledge of WPF and XAML has been assumed.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub athttps://github.com/PacktPublishing/Windows-Presentation-Foundation-Development-Cookbook. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: https://www.packtpub.com/sites/default/files/downloads/WindowsPresentationFoundationDevelopmentCookbook_ColorImages.pdf.
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "The Presentation Core layer, part of presentationcore.dll, provides you with the wrapper around the Media Integration Library."
A block of code is set as follows:
<Button> <Button.Background> <SolidColorBrush Color="Red" /> </Button.Background> </Button>
Any command-line input or output is written as follows:
svcutil.exe http://localhost:59795/Services/EmployeeService.svc?wsdl
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "To build WPF applications targeting the .NET Framework, select the .NET desktop development workload."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
In this chapter, we will cover the following recipes:
Installing WPF Workload with Visual Studio 2017
Creating WPF applications
Creating and navigating from one window to another
Creating and navigating from one page to another
Creating a dialog box
Creating ownership between windows
Creating a single instance application
Passing arguments to WPF applications
Handling unhandled exceptions
The Windows Presentation Foundation (WPF) provides developers with a unified programming model to build dynamic, data-driven desktop applications for Windows. It was first released in 2006 along with .NET 3.0. It is part of the .NET Framework itself.
WPF is a graphical subsystem, for rendering rich user interfaces (UIs), and is a resolution-independent framework that uses a vector-based rendering engine in theExtensible Application Markup Language(XAML) to create stunning user interfaces. It supports a broad set of features that includes application models, controls, layouts, graphics, resources, security, and more.
The runtime libraries for it to execute have been included with Windows since Windows Vista and Windows Server 2008. If you are using Windows XP with SP2/SP3 and Windows Server 2003, you can optionally install the necessary libraries.
To begin learning the different recipes of WPF, you should have a clear understanding of the basic foundations. In this chapter, we will start with the architecture and syntaxes, and will guide you in creating a building block.
WPF uses a layered architecture that includes managed, unmanaged, and the core APIs in five different layers called Presentation Framework, Presentation Core, Common Language Runtime, Media Integration Library, and OS Core. The programming model is exposed through the managed code.
In the following diagram, you can see a clear picture of the architecture:
The Presentation Framework, which is part of presentationframework.dll, provides the basic required components (such as controls, layouts, graphics, media, styles, templates, animations, and more) to start building the UIs of your WPF applications. It is part of the managed layer.
The Presentation Core layer, part of presentationcore.dll, provides you with the wrapper around the Media Integration Library (MIL). It present you with the public interfaces to access the MIL Core and the Visual System to develop the Visual Tree. It contains visual elements and rendering instructions to build applications for Windows using the XAML tools. This is also part of the managed code.
Common Language Runtime, commonly known as the CLR and part of the managed layer, provides you with several features to build robust applications covering common type system (CTS), error handling, memory management, and more.
The Media Integration Library (MIL), which resides in milcore.dll, is part of the unmanaged layer used to display all graphics rendered through the DirectX engine. It provides you with basic support for 2D and 3D surfaces, and allows you to access the unmanaged components to enable tight integrations with DirectX. It also enables you to gain performance while rendering instructions from the Visual System to the Common Language Runtime (CLR).
Just after the MIL, the next layer is the OS Core, which provides you with access to the low-level APIs to handle the core components of the operating system. This layer includes Kernel, User32, DirectX, GDI, and device drivers.
Though WPF is mainly used for desktop applications, you can also create web-based applications. Thus, WPF applications can be of two types:
Desktop-based executables (EXE)
Web-based applications (XBAP)
The desktop applications are the normal .exe executables, which you normally run on any of your Windows-based systems, whereas the web-based applications are the .xbap files that can be deployed in web servers and can run inside any supported browser. The .NET Framework is mandatory to run any of these application types.
When you run a WPF application, it starts in two threads. The UI thread uses the System.Threading.DispatcherObject to create the messaging system and that maintains the UI operations queue. Just like the Win32 message pumping, it performs the UI operation based on the priority set for it.
The other thread is the background thread, which is used to handle the rendering engine being managed by WPF. It picks up a copy of the visual tree and performs actions to show the visual components in the Direct3D surface. Then it calls the UI elements to determine the size and arranges the child elements by their parents.
XAML stands for Extensible Application Markup Language. It is an XML-based markup language that is used to declaratively create the UI of any XAML-based application, such as Windows Platform Foundation (WPF), Universal Windows Platform (UWP), and Xamarin.Forms. You can create visible UI elements in a declarative XAML syntax to design the rich UI and then write the code behind to perform a runtime logic.
Though it is not mandatory to use the XAML markup to create a UI, it has been widely accepted as the smart option for the creation of the entire application's UI, as it makes things easier to create. You can create the UI by writing C# or VB.NET code too, but that makes it more difficult and tougher to maintain. Also, that makes it difficult for the designers to work independently.
Designing an application UI using XAML is as easy as writing an XML node with a few optional attributes. Attributes are used to set additional styles, behaviors, and properties. To create a simple button in the UI, you can just write <Button /> in your XAML file. Similarly, you can just write <TextBox /> to create a user-input box.
Additionally, you can add more details to the controls. For example, to add a label to a button, use its Content property, and to set its dimension, use the Height and Width property, as shown in the following code:
<Button Content="Click Here" /> <Button Height="36" Width="120" />
In general, when you add XAML pages to your WPF application project, it compiles along with the project and produces a binary file in what is known as Binary Application Markup Language (BAML). The final output of the project (that is, the assembly file) contains this BAML file as a resource. When the application loads into the memory, the BAML is then parsed at runtime.
You can also load an XAML into memory and directly render it on the UI. But, in this case, if it has any XAML syntax errors, it will throw those in runtime. If you compare the performance with the first process, the latter is slower, as it renders the entire XAML syntax onto UI.
Here's a flow diagram, that demonstrates the ways to load and render/parse the XAML UI:
XAML uses some syntax terminologies to define an element in the UI and create the instance of it. Before you start working on it, you must understand the different terminologies that it offers. Let's have a look at a few of them.
Each instance of a type is defined using proper XAML syntax to create an object element in the UI. Each of these object elements starts with a left angular bracket (<) and defines the name of the element. You can optionally prefix the namespace when it is defined outside the default scope. You can use a self-closing angular bracket (/>) or a right angular bracket (>) to close the object element definition. If the object element does not have any child elements, the self-closing angular bracket is used. For example, (<Button Content="Click Here" />) uses a self-closing angular bracket. If you write the same with a child element, it closes with an end tag (<Button>Click Here</Button>,) as shown.
When you define the object element in an XAML page, the instruction to create the instance of the element gets generated and it creates the instance by calling the constructor of the element when you load it in memory.
You can define one or more properties to an element. These are done by writing an attribute called Property Attribute syntax to the element. It starts with the name of the property and an assignment operator (), followed by the value within quotes. The following example demonstrates how easy it is to define a button element to have a label as its content, and how to set its dimension in UI:
<Button Content="Click Here" /> <Button Content="Click Here" Width="120" Height="30" />
This is another type of XAML syntax that allows you to define the property as an element. This is often used when you cannot assign the value of the property within quotes. If we take the previous example, the text Click Here can be assigned to the button content easily. But, when you have another element or a composite property value, you cannot write those within the quotes. For this, XAML introduces Property Element syntax to help you to define the property value easily.
It starts with <element.PropertyName> and ends with </element.PropertyName>. The following example demonstrates how to assign a color to a button background with a SolidColorBrush object:
<Button> <Button.Background> <SolidColorBrush Color="Red" /> </Button.Background> </Button>
This is another type of XAML syntax that is used to set the content of a UI element. It can be set as the value of child elements. The following example demonstrates how to set the text content property of a Border control to hold a Button control as its child element:
<Border> <Border.Child> <Button Content="Click Here" /> </Border.Child> </Border>
While using Content syntax, you should remember the following points:
The value of a
Content
property must be contiguous
You cannot define an XAML
Content
property twice within a single instance
Thus, the following is invalid as it will throw XAML error:
<Border> <Border.Child> <Button Content="Button One" /> </Border.Child> <Border.Child> <Button Content="Button Two" /> </Border.Child> </Border>
When you need to define a collection of elements to the parent root, the Collection syntax is used to make it easy to read. For example, to add elements inside StackPanel, we use its Children property, as shown in the following code:
<StackPanel> <StackPanel.Children> <Button Content="Button One" /> <Button Content="Button Two" /> </StackPanel.Children> </StackPanel>
This can be also written as follows, and the parser knows how to create and assign the elements to StackPanel:
<StackPanel> <Button Content="Button One" /> <Button Content="Button Two" /> </StackPanel>
When you add a button, you need to associate an event listener to it, to perform some operation. The same is applicable for adding other controls and UI layouts. The XAML allows you to use the Event Attribute syntax to define events for a specific XAML object element.
The syntax looks like a property attribute, but it is used to associate the event listener to the element. The following example demonstrates how to assign the click event to a button control:
<Button Content="Click Here" Click="OnButtonClicked" />
The associated event gets generated from the code behind the XAML page, where you can perform the real action. Here is the code snippet for the event implementation of the preceding button-click event:
void OnButtonClicked (object sender, RoutedEventArgs e) { // event implementation }
As we have learned the basic concepts of WPF Architecture and XAML syntax, we can start to learn different recipes to build applications for Windows using the XAML tools for WPF. But, before that, let's install the required workload/components for Visual Studio 2017. If you are using prior versions of Visual Studio, this step will be different.
To install the required components for building WPF applications, run the Visual Studio 2017 installer. If you don't have the installer, you can go to https://www.visualstudio.com/downloads and download the correct edition. Let's download the Visual Studio Community 2017 edition as it is a fully featured IDE and available free for students, open source, and individual developers.
Once you have downloaded the Visual Studio 2017 installer, follow these steps to install the correct workload:
Once you have run the installer, it will show you the following screen. Click on
Continue
:
Wait for a few minutes to let the installer prepare itself for the installation process. A progress bar will show you the status of the current progress:
Then the following screen will pop up, where it will ask you to select the
workloads
or
components
that you want to install:
To build WPF applications targeting .NET Framework, select the
.NET desktop development
workload, as shown in the preceding screenshot.
Click on the
Install
button to continue with the installation.
The following screen will be displayed, showing the status of the installation. It will take some time, based on your internet bandwidth, as it's going to download the required components, based on your selection, from the Microsoft servers and install them one by one:
Once the installation has completed, you may have to restart your system for the changes to take effect. In this case, a popup will appear on the screen, asking you to reboot your PC.
Once you have installed the .NET desktop development component and restarted your system, you are good to go with building your first WPF application.
The WPF development platform supports a broad set of features that includes UI controls, layouts, resources, graphics, data binding, application model, and more. Before using each of those features, you need to create the WPF project using Visual Studio.
The goal of this recipe is to create a WPF project and learn the basic project structure and components. Let's start building our first WPF application using the XAML tools.
To get started with the WPF application development, you must have Visual Studio running on your system with the required components already installed on it.
Follow these steps to create your first WPF application:
Inside your Visual Studio IDE, navigate to the
File
|
New
|
Project...
menu as shown in the following screenshot:
This will open the
New Project
dialog on the screen. You can alternatively open it by pressing the keyboard shortcut
Ctrl
+
Shift
+
N
.
In the
New Project
dialog, navigate to
Installed
|
Templates
|
Visual C#
|
Windows Classic Desktop
, as shown in the left-hand side of the following screenshot:
In the right-hand side panel, first select the
.NET Framework
that you want your application to target. We have selected
.NET Framework 4.7
here.
Then select
WPF App (.NET Framework)
, from the available list of templates.
Give a name (in our case, it is
CH01.HelloWPFDemo
) to the project.
Optionally, select the location of the project, where you want to create it.
Optionally, you can also provide a different name for the
Solution
.
When you are ready, click on the
OK
button to let Visual Studio create the project based on the template that you have selected.
Once the project has been created, Visual Studio will open the Solution Explorer, which lists the project with all the default files created on it. The project structure will look like the following screenshot:
Each WPF application project created by Visual Studio using the default template consists of the following files:
App.config
: This is the configuration file of your WPF application. By default, it contains the following lines that describe the supported runtime version for the application to run. This contains exactly the same runtime version that we selected during the project creation:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0"sku=".NETFramework,Version=v4.7" /> </startup> </configuration>
The config file can also contain application settings and other configuration settings that you want to use/refer in your application.
App.xaml
: Visual Studio automatically creates the
App.xaml
file when you create a WPF project. It is the declarative starting point of your application. The root element of this file is the
Application
instance, which defines application specific properties and events:
<Application x:Class="CH01.HelloWPFDemo.App" xmlns="http://schemas.microsoft.com/winfx /2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:CH01.HelloWPFDemo" StartupUri="MainWindow.xaml"> <Application.Resources> </Application.Resources> </Application>
The instance of the Application class defines the Window or a Page that's going to be the startup UI, and is registered with the StartupUri property. In the preceding code, (StartupUri="MainWindow.xaml") states that the MainWindow.xaml page will get loaded, once you run the application.
The application instance can also hold global/application-level resources (such as, Style, Template, and Converter) that can be used globally throughout the application.
App.xaml.cs
: This is the code-behind class file of the
App.xaml
and extends the
Application
class of the framework to write application-specific code. You can use this file to subscribe to the events such as
Startup
,
UnhandledException
to perform common operations:
namespace CH01.HelloWPFDemo { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
This class is often used to manipulate command-line parameters and load different XAML pages based on that.
MainWindow.xaml
: This is the default UI page that Visual Studio generates on creation of the WPF project. It is the page that gets registered as the
StartupUri
in
App.xaml
. The root element of this page is
Window
and it contains a
Grid
layout by default. Here is the default code snippet:
<Window x:Class="CH01.HelloWPFDemo.MainWindow" xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525"> <Grid> </Grid> </Window>
The x:Class attribute defines the associated partial class where the UI logic is being written. You can modify this XAML to provide a fresh look to your application start page. Various UI controls and layouts are going to be covered in the later chapters of this book.
MainWindow.xaml.cs
: This is the code-behind class of
MainWindow.xaml
and contains the logic related to UI operations. In general, developers write implementations of various UI operations in this class.
Whenever you add any UI elements to an XAML page, the control gets registered internally in a partial class file that has .g.i.cs as the extension. For example, if you add a control in the MainWindow.xaml file, it gets registered in the MainWindow.g.i.cs residing in the obj folder. If you open the file, you can observe the entire loading process inside the InitializeComponent() method.
In WPF standalone applications, a window is used to host the UI elements to enable users to interact with the UI and data. The base class Window provides all the APIs to create and interact with the Window UI.
In WPF applications, the generic window layout is divided into multiple parts. Here is a screenshot of a basic window, containing its various parts:
The various parts of the window are as mentioned here:
The outer part of the window is a
Border
, which you can utilize to enable the resizing option:
The outer border can contain a
resizing grip
, which enables you to resize the window diagonally
The window contains a
Title bar
at the top, which consists of the following parts:
An
Icon
to provide a unique brand to your application window
A
Title
, showing the identifiable name of the window
A small panel, containing
Minimize
,
Maximis
e
/
Restore
, and
Close
buttons
A
System menu
with menu items to allow users to perform
Minimize
,
Maximize
/
Restore
,
Mov
e,
Size
, and
Close
operations on the window
A
client area
for the developers to add application/window specific layouts and controls
To get started with this recipe, open your Visual Studio instance and create a WPF project called CH01.WindowDemo based on the WPF App (.NET Framework) template. Once the project has been created, it will have files called MainWindow.xaml and MainWindow.xaml.cs, along with the other default files.
Let's get started with creating a new window in the same project and invoke a button to open the new window from the MainWindow.
To create a new window, follow these simple steps:
Open the
Solution Explorer
and right-click on the project node.
From the right-click context menu, navigate to
Add
|
Window...
as shown in the following screenshot:
The following
Add New Item
