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 4.5 Cookbook
Windows Presentation Foundation 4.5 Cookbook

Windows Presentation Foundation 4.5 Cookbook: For C# developers, this book offers a fast route to getting more closely acquainted with the ins and outs of Windows Presentation Foundation. The recipe approach smoothes out the complexities and enhances learning.

eBook
$35.98 $39.99
Paperback
$65.99
Subscription
Free Trial
Renews at $19.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 4.5 Cookbook

Chapter 1. Foundations

In this chapter we will cover the following:

  • Creating custom type instances in XAML

  • Creating a dependency property

  • Using an attached property

  • Creating an attached property

  • Accessing a static property in XAML

  • Creating a custom markup extension

  • Handling routed events

Introduction


Any attempt at mastering a technology, any technology, requires a good understanding of its foundations. This understanding makes it possible to grasp the more complex aspects of that technology; Windows Presentation Foundation (WPF) is no different.

In this first chapter, we'll discuss recipes concerning the very foundations of WPF – what makes it tick—and also along the way, what makes it unique.

XAML

The first noticeable facet of WPF is XAML (eXtensible Markup Language). XAML is an XML based language used in WPF to declaratively create user interfaces. Actually, XAML has nothing to do with UI. It's merely a declarative way of constructing objects and setting their properties. In fact, it's leveraged in other technologies, such as the Windows Workflow Foundation (WF), where it's used as a way of constructing workflows. To create objects in XAML, they must be "XAML friendly" – meaning they must have the following:

  • A public default constructor

  • Settable public properties

The second item is not strictly a requirement, but the lack of settable properties would make the object a bit dull. Note that starting with .NET 4, XAML is in fact capable of handling parameterized constructors, but WPF's XAML parser currently does not leverage that capability.

XAML is not an absolute requirement. In fact, you can create an entire application using C# or VB (or whichever .NET language you fancy) without a single XAML tag. However, that would be much more difficult and error prone with high maintenance costs, not to mention the difficulty of integration with your fellow designers.

XAML is about the what, not the how. This declarative style makes things easier (granted, after some getting used to), and is a paradigm shift in software development in general (the classic example in .NET being the LINQ-based technologies). XAML is neutral—it's not C# or anything like that—so other, non-developer tools can create or manipulate it. Microsoft provides the Expression Blend tool, which at its core, is a glorified XAML producer/consumer.

XAML and compilation

What happens to a XAML file? How is it tied to the code behind file created by Visual Studio? A XAML file is compiled by a XAML compiler that produces a binary version of the XAML, known as BAML. This BAML is stored as a resource inside the assembly and is parsed at runtime in the InitializeComponent call to create the actual objects. The result is bundled with the code behind file (the typical Window class is declared as partial, meaning there may be more source files describing the same class) to produce the final code for that class.

Browsing a typical WPF application, we won't find the canonical Main method, because it's generated by WPF. It constructs the singleton Application object instance and creates the first window specified by the Application.StartupUri property (if not null). We can find that code in the file App.g.cs (g stands for generated) inside the Obj\x86\Debug sub-folder.

Dependency properties

.NET properties are nothing more than syntactic sugar over set and get methods. What those methods do is up to the property's developer. More often than not, a property is a thin wrapper over a private field, perhaps adding some validation logic in its setter.

WPF requires more out of its properties. Specifically, WPF's dependency properties provide the following:

  • Change notifications when the property's value is changed.

  • Validation handler called as part of a set operation.

  • Coercion handler that is able to "coerce" the provided value to an acceptable value.

  • Various providers can attempt to set the property's value, but only one such provider wins at a time. Nevertheless, all values are retained. If the winning provider goes away, the property's value is set to the next winner in line.

  • Property value inheritance down the visual tree (if so desired).

  • No memory is allocated for a property's value if that value is never changed from its default.

These features provide the basis of some of WPF's strong features, such as data binding and animation.

On the surface, these properties look the same as any other property—a getter and a setter. But no private fields are involved, as we'll see in the following recipes.

Creating custom type instances in XAML


Sometimes there's a need to create instances of your own types, or other .NET Framework, non-WPF types within XAML. A classic example is a data binding value converter (which we'll explore in Chapter 6, Data Binding, but other scenarios might call for it).

Getting ready

Make sure you have Visual Studio 2010 up and running.

How to do it...

We'll create a simple application that creates an instance of a custom type in XAML to demonstrate the entire procedure:

  1. Create a new WPF Application project named CH01.CustomTypes.

  2. Let's create a custom type named Book. In the Solution Explorer window, right-click on the project node and select Add and then Class…:

  3. Type Book in the Name box and click on Add:

  4. Add four simple properties to the resulting class:

    class Book {
       public string Name { get; set; }
       public string Author { get; set; }
       public decimal Price { get; set; }
       public int YearPublished { get; set; }
     }

    Tip

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the files e-mailed directly to you.

  5. Open the MainWind w.xaml file (using the Solution Explorer), which was created automatically by the project wizard. We would like to create an instance of the Book class. As a Book is not an element (does not derive from UIElement), we cannot simply create it inside our Grid. But, we can make it the Content property (that can be anything, as its type is Object) of a ContentControl-derived type, such as Button. Add a button control to the existing grid, as follows:

    <Grid>
        <Button FontSize="20">
        </Button>    
    </Grid>
  6. To create an instance of Book, we first need to map the .NET namespace (and assembly) where Book is defined to an XML namespace that can be used by the XAML compiler. Let's add a mapping at the top of the XAML near the default mappings added by the application wizard:

    <Window x:Class="CH01.CustomTypes.MainWindow"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:local="clr-namespace:CH01.CustomTypes"
    
  7. This says that anything prefixed by the string local (we can select anything here), should be looked up in the CH01.CustomTypes namespace (in the current assembly).

  8. Now, we can finally create a Book instance. Add the following inside the Button tag:

    <Button FontSize="20">
       <local:Book Name="Windows Internals" 
       Author="Mark Russinovich" Price="40" 
       YearPublished="2009" />
    </Button>    
  9. That's it. We can verify this by adding a suitable ToString implementation to the Book type, and running the application:

    public override string ToString() {
    return string.Format("{0} by {1}\nPublished {2}", Name, 
          Author, earPublished); 
    
    }

How it works...

The XAML compiler needs to be able to resolve type names such as Button or Book. A simple name like Button is not necessarily unique, not in the XML sense and certainly not in the .NET sense (there are at least four Button types in .NET, naturally in diffrent namespaces) .

A mapping is required between an XML namespace and a .NET namespace, so that the XAML compiler can reference the correct type. By default, two XML namespaces are declared by a typical XAML file: the first, which is the default XML namespace, is mapped to the normal WPF namespaces (System.Windows, System.Windows.Controls, and so on). The other, typically with the x prefix, is mapped to the XAML namespace (System.Windows.Markup).

For our own types, we need to do similar mapping (but with a different syntax) means map the XML namespace prefix local to the .NET namespace CH01.CustomTypes. The following line:

xmlns:local="clr-namespace:CH01.CustomTypes"

This allows our Book class to be recognized and used within the XAML.

If the type was defined in a referenced assembly (not our own assembly), then the mapping would continue to something like the following:

xmlns:local="clr-namespace:CH01.CustomTypes;assembly=MyAssembly"

For example, suppose we want the ability to create instances of the System.Random type. Here's how we'd map an XML namespace to the .NET namespace and assembly where Sys em.Random resides:

xmlns:sys="clr-namespace:System;assembly=mscorlib"

Now, we could create an instance of anything in the System namespace (that is XAML friendly) and the mscorlib assembly (such as Random):

 <sys:Random x:Key="rnd" />

In this case, it's hosted in a ResourceDictionary (which is a kind of dictionary, meaning every value requires a key; we'll discuss these in more detail in the next chapter).

There's more...

It's possible to map a single XML namespace to multiple .NET namespaces. This is the same technique used by the WPF assemblies itself: a single XML namespace maps to multiple WPF namespaces, such as System.Windows, System.Windows.Controls, and System.Wind ws.Media.

The trick is to use the XmlnsDefinition attribute within the assembly where the exported types reside. This only works for referenced assemblies; that is, it's typically used in class library assemblies.

For example, suppose we create a MyClassLibrary class library assembly, with a type like the Book introduced earlier:

namespace MyClassLibrary {
   public class Book {
      public string Name { get; set; }
      public string Author { get; set; }
      public decimal Price { get; set; }
      public int YearPublished { get; set; }
   }
}

We can make all types within this assembly and the MyClassLibrary namespace part of an XML namespace by adding the following attribute:

[assembly: XmlnsDefinition("http://mylibrary.com",
"MyClassLibrary")]

The first argument to the attribute is the XML namespace name. This can be anything, but is typically some form of fictitious URL (usually a variation on the company's URL), so as to lower chances of collisions (this is exactly the same idea used by WPF). The second string is the .NET namespace mapped by this XML namespace.

Now, suppose we have another .NET namespace within that same assembly with some types declared within it:

namespace MyClassLibrary.MyOtherTypes {
   public class MyType1 {
      //...
   }
 
   public class MyType2 {
      //...
   }
}

We can add another attribute to map the same XML namespace to the new .NET namespace:

[assembly: XmlnsDefinition("http://mylibrary.com", "MyClassLibrary.MyOtherTypes")]

This means that a single XML prefix (in some client application) can now map to multiple .NET namespaces:

xmlns:mylib="http://mylibrary.com" 

This scheme can save multiple distinct XML prefix declarations. One consequence of this idea is that all public type names must be unique across the mapped .NET namespaces (as they are indeed within WPF itself).

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Full of illustrations, diagrams, and tips with clear step-by-step instructions and real world examples
  • Gain a strong foundation of WPF features and patterns
  • Leverage the MVVM pattern to build decoupled, maintainable apps

Description

Windows Presentation Foundation (WPF) provides developers with a unified programming model for building rich Windows smart client user experiences that incorporate UI, media, and documents.WPF has become the leading technology for developing rich client applications on the Windows platform, packed with features and capabilities. However, WPF is big; in fact, it's huge, causing a steep learning curve for the beginner and even for those already using some WPF features.Windows Presentation Foundation 4.5 Cookbook provides clear recipes for common WPF tasks. It includes detailed explanations and code examples for customizing and enhancing the basic scenarios, while gaining a deep understanding of WPF mechanics and capabilities.WPF is different and requires a different mind-set and approach. This book provides recipes and insights not only in its design but also its practical implementation details.Starting from the foundations of WPF, such as dependency properties and XAML, the book touches on all major WPF aspects, such as controls and layout, resources, and digs deep into its unprecedented data binding capabilities.The book shows data and control templates in action, which allow full customizations of displayed data and controls in a declarative way. Supported by styles and resources makes data binding all the more powerful. The Model View View-Model pattern is presented as an effective way of maximizing decoupling of components, while providing an elegant way of expanding applications while maintaining a tight grip on complexity.The later parts discuss custom elements and controls ñ the ultimate customization mechanism, and looks at multithreading issues, and how .NET 4.5 task parallelism features can enhance application performance.

Who is this book for?

If you are C# developer looking forward to increasing your understanding and knowledge of WPF, then this is the best guide for you. Basic experience with Visual Studio 2010 is mandatory, as well as good C# skills. Previous experience with Windows Forms is not required.

What you will learn

  • Get tips and insights to maximize your productivity
  • Learn to build complex and flexible user interfaces using XAML
  • Perform lengthy operations asynchronously while keeping the UI responsive
  • Get well-versed with WPF features such as data binding, layout, resources, templates, and styles
  • Customize a control s template to alter appearance but preserve behaviour

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 25, 2012
Length: 464 pages
Edition : 1st
Language : English
ISBN-13 : 9781849686235
Vendor :
Microsoft
Languages :

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 : Sep 25, 2012
Length: 464 pages
Edition : 1st
Language : English
ISBN-13 : 9781849686235
Vendor :
Microsoft
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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
$279.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 $ 186.97
Windows Presentation Foundation Development Cookbook
$65.99
MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF
$54.99
Windows Presentation Foundation 4.5 Cookbook
$65.99
Total $ 186.97 Stars icon

Table of Contents

11 Chapters
Foundations Chevron down icon Chevron up icon
Resources Chevron down icon Chevron up icon
Layout and Panels Chevron down icon Chevron up icon
Using Standard Controls Chevron down icon Chevron up icon
Application and Windows Chevron down icon Chevron up icon
Data Binding Chevron down icon Chevron up icon
Commands and MVVM Chevron down icon Chevron up icon
Styles, Triggers, and Control Templates Chevron down icon Chevron up icon
Graphics and Animation Chevron down icon Chevron up icon
Custom Elements Chevron down icon Chevron up icon
Threading 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.4
(30 Ratings)
5 star 73.3%
4 star 10%
3 star 3.3%
2 star 6.7%
1 star 6.7%
Filter icon Filter
Top Reviews

Filter reviews by




Radovan Sep 19, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I originally learned WPF/XAML haphazardly from the web. This book was great for filling my knowledge gaps; it presents advanced topics in plain language. It's extremely well written and covers just about everything. If you're a beginner, recommend doing some tutorials and a small project first.
Amazon Verified review Amazon
Stephen D. Holle Sep 30, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I've tried a number of tutorials on WPF and always got stuck on the XAML end of it. The step-by-step method with clear explanations used in this book got me over the hump. I'm keeping this one around as a reference.
Amazon Verified review Amazon
book guru Apr 30, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Great book. The author explains things very well. I would have liked some more coverage of the MVVM pattern as this was the main reason I purchased the book. Having said that, there aren't many other books with good reviews that cover MVVM. There are some that are dedicated to MVVM but have bad reviews. I considered "C# 6.0 and the .NET 4.6 Framework" but the MVVM coverage is even less. I will consider getting "Learn WPF MVVM". Again, the other does a great job explaining things so check the online content page and the amount of coverage each topic gets.
Amazon Verified review Amazon
T. Ray Humphrey Jun 14, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
So many books I've found on WPF cover XAML, of course, but then seem to focus on cool UI features. Data binding gets a passing mention with regard to UI elements but an in-depth treatment is missing. I write business apps and have a data model to bind to my UI. I need to bind objects and sets of objects, and I've found most WPF books lacking in this area. Before this book, my best source was a book on writing Silverlight business applications (poor, dead Silverlight!). I actually bought this book because of a few recipes about business data model binding, but found so much more. I started reading it from the beginning and learned something in every single solution. The author has a great style and explains things clearly.In our current tech world, where product documentation is basically crowd-sourced to third-party forum sites like Stack Exchange, it is often hard to find a source that presents a cohesive view of a product. Don't get me wrong, I love Stack Exchange and use it a lot, but the bigger picture can be lost in code snippets. As this is a cookbook, there is lots of code to look at, but the surrounding text gives a great context for the problem being solved, and I learned some foundational pieces about WPF along the way.Great book!
Amazon Verified review Amazon
Karl Feb 16, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
So far I have purchased:PRO WPF 4.5 in C#,WPF 4.5 Unleashed,and MVVM survival guide for Enterprise etc..(These are pretty much the only books out there)I have to say this book is the best of them all. I haven't written any reviews for the other books only this one. That's how much i like this book. Trust me if you're new to WPF this book is the best one. Although Pro WPF 4.5 is also very good although it has more information than you really need.High Points of this book:1) Less Garbage to filter out. (I hate it when books go into sooooo much detail that it loses focus)2) Great Step by step guide3) Great Sample projects that are in individual projects(This makes figuring out what's going in the projects so much better, and believe me that this book hasTHE BEST SAMPLE PROJECTS!)4) Over all breakdown Getting Ready Section: Very detailed and easy to follow. Other books just assume you know how to set everything up. How It Works Section: This is very helpful and to the point.OVERALL:I have been studying WPF for about 6 months now and i will tell you that it's not easy to get into. There is a MAJOR learning curve to this. This book is it's well organized, and to the point.
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.