Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Windows Presentation Foundation Development Cookbook
Windows Presentation Foundation Development Cookbook

Windows Presentation Foundation Development Cookbook: 100 recipes to build rich desktop client applications on Windows

eBook
€35.98 €39.99
Paperback
€49.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Windows Presentation Foundation Development Cookbook

WPF Fundamentals

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

Introduction

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 the Extensible 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.

The WPF Architecture

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:

Presentation Framework

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.

Presentation Core

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

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.

Media Integration Library

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).

OS Core

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.

Types of WPF applications

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.

The XAML overview

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.

Microsoft recently introduced XAML Standards, which is a specification that defines a standard XAML vocabulary, which will allow the supported frameworks to share common XAML-based UI definitions.

You can learn more about this specification by visiting GitHub here:
http://aka.ms/xamlstandard.

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 syntax terminologies

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.

Object element syntax

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.

Property Attribute syntax

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" /> 

Property Element syntax

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> 

Content syntax

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> 

Collection syntax

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> 

Event Attribute syntax

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 
    } 

Installing WPF Workload with Visual Studio 2017

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.

Getting ready

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.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Gain a strong foundation in WPF features and patterns
  • Leverage the MVVM pattern to build decoupled, maintainable apps
  • Increase efficiency through Performance tuning and UI automation

Description

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.

Who is this book for?

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.

What you will learn

  • Understand the fundamentals of WPF
  • Explore the major controls and manage element layout
  • Implement data binding
  • Create custom elements that lead to a particular implementation path
  • Customize controls, styles, and templates in XAML
  • Leverage the MVVM pattern to maintain a clean and reusable structure in your code
  • • Master practical animations
  • • Integrate WCF services in a WPF application
  • • Implement WPFs support for debugging and asynchronous operations

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 23, 2018
Length: 524 pages
Edition : 1st
Language : English
ISBN-13 : 9781788396356
Concepts :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Feb 23, 2018
Length: 524 pages
Edition : 1st
Language : English
ISBN-13 : 9781788396356
Concepts :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 144.97
Mastering Windows Presentation Foundation
€45.99
Windows Presentation Foundation Development Cookbook
€49.99
Windows Presentation Foundation 4.5 Cookbook
€48.99
Total 144.97 Stars icon

Table of Contents

12 Chapters
WPF Fundamentals Chevron down icon Chevron up icon
Using WPF Standard Controls Chevron down icon Chevron up icon
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 Chevron down icon Chevron up icon
Working with Data Bindings Chevron down icon Chevron up icon
Using Custom Controls and User Controls Chevron down icon Chevron up icon
Using Styles, Templates, and Triggers Chevron down icon Chevron up icon
Using Resources and MVVM Patterns Chevron down icon Chevron up icon
Working with Animations Chevron down icon Chevron up icon
Using WCF Services Chevron down icon Chevron up icon
Debugging and Threading Chevron down icon Chevron up icon
Interoperability with Win32 and WinForm Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(12 Ratings)
5 star 75%
4 star 0%
3 star 8.3%
2 star 8.3%
1 star 8.3%
Filter icon Filter
Top Reviews

Filter reviews by




superticker Oct 04, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was originally reluctant to buy a "cookbook" style textbook for introductory purposes because of the haphazard organization of the "recipes" listed inside. And _within_ a chapter, the organization is somewhat haphazard as expected. But the ordering of the chapters themselves is very well done and layered.The problem with an "integrated organization" is that too much material gets thrown at the reader at once making it hard to separate the trees from the forest. With the cookbook styling, each aspect is dissected separately bringing it into focus. And that makes learning easier in this complex context. Yes, the integration of the material between chapters is left more to the reader, but it's not too hard to connect the dots.The reader should have a command knowledge of C# and some prior experience with Visual Studio.The publisher has a website for downloading the examples. There's also a GitHub link with the latest code fixes to the examples.
Amazon Verified review Amazon
Amazon Customer May 11, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Kunal does a fantastic job in laying down a strong foundation for laerning WPF in the first few chapters and goes on to deliver a solid, well-rounded book that covers all the bases. If you have always wanted to get into Windows Presentation Foundation, then you should consider reading his book.Personally, I like the cookbook approach. This book contains many "recipes" allowing the reader to become familiar with the topic. Later chapters are a bit more in depth, showing you how to work with animations and discussing MVVM patterns. I really enjoyed the spread of the chapters, covering a nice portion of WPF.Lastly, Kunal is one of the few authors that delivers superb screenshots... annotating them well so that there is no ambiguity in his explaination of the topic. For me, not professionally having worked much with WPF in the past (apart from the odd pet project), this book definitely belongs on my bookshelf.
Amazon Verified review Amazon
深淵の機械 Aug 15, 2019
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've found this book extremely helpful as a new Developer. Unlike many other similar titles, it's clear, concise and easy to follow.
Amazon Verified review Amazon
JBL Jun 20, 2020
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This book is great if you're just starting out with WPF. The content consists of code examples (both C# and XAML) with explanations in between. Overall, I would say the majority of this book focuses on the UI of an application.The physical condition of this book is good. The text is clear and easy to read and the pages don't stick together.While this is technically an intro book, there are a few tips here and there that could easily be overlooked if you're used to using the official Microsoft documentation.
Amazon Verified review Amazon
Alvin Ashcraft Mar 08, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I was the technical reviewer of this book and would like to provide a review of it from my perspective.This "cookbook" style WPF book is a great resource for software developers with a mid-level (or less) understanding of WPF development. More experienced developers will probably still learn a few things, but most of the content is best for those with less experience on the platform. The cookbook format divides lessons into "recipes" with a familiar and consistent approach to teaching the core concepts of WPF development.Every concept that is needed to get up and going with WPF is covered in the book, from controls to binding to styles & templates to MVVM concepts. Later chapters cover more advanced topics like calling WCF services, threading and interop.There are not many current titles for WPF developers out there. I was really happy to see Packt decided to put an updated resource out for today's desktop Windows developer.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.