Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
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.

Arrow left icon
Profile Icon Pavel Yosifovich
Arrow right icon
₱1885.99 ₱2694.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (30 Ratings)
eBook Sep 2012 464 pages 1st Edition
eBook
₱1885.99 ₱2694.99
Paperback
₱3367.99
Subscription
Free Trial
Arrow left icon
Profile Icon Pavel Yosifovich
Arrow right icon
₱1885.99 ₱2694.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (30 Ratings)
eBook Sep 2012 464 pages 1st Edition
eBook
₱1885.99 ₱2694.99
Paperback
₱3367.99
Subscription
Free Trial
eBook
₱1885.99 ₱2694.99
Paperback
₱3367.99
Subscription
Free Trial

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 2. Resources

In this chapter we will cover:

  • Using logical resources

  • Dynamically binding to a logical resource

  • Using user selected colors and fonts

  • Using binary resources

  • Accessing binary resources in code

  • Accessing binary resources from another assembly

  • Managing logical resources

Introduction


Traditional application resources consist of binary chunks of data, typically representing things such as icons, bitmaps, strings, and XML. In fact, the .NET framework provides generic support for these through the ResourceManager class.

WPF is no different—binary resources play an important role in a typical application. However, WPF goes a lot further with another kind of resource: logical resources. These are objects, any objects, which can be shared and used in a multitude of locations throughout the application; they can even be accessed across assemblies. Some of WPF's features, such as implicit (automatic) styles and type-based data templates, rely on the logical resources system.

In this chapter, we'll take a look at resources, binary and logical, their definition, and usage in XAML and code, and discuss various options and typical scenarios, such as combining resources (even across assemblies) and resource lookup and modifications.

Using logical resources


WPF introduces the concept of logical resources, objects that can be shared (and reused) across some part of a visual tree or an entire application. Logical resources can be anything, from WPF objects such as brushes, geometries, or styles, to other objects defined by the .NET Framework or the developer, such as string, List<>, or some custom typed object. This gives a whole new meaning to the term resources. These objects are typically placed inside a ResourceDictionary and located at runtime using a hierarchical search, as demonstrated in this recipe.

Getting ready

Make sure Visual Studio is up and running.

How to do it...

We'll create a simple application that demonstrates creating and using logical resources:

  1. Create a new WPF Application named CH02.SimpleResources.

  2. Open MainWindow.xaml and replace the Grid element with a StackPanel.

  3. Add a Rectangle element to the StackPanel, as shown in the following code snippet:

         <Rectangle Height="100" Stroke="Black"&gt...

Dynamically binding to a logical resource


As we saw in the previous recipe, Using logical resources, binding to a resource is achieved in XAML by using the StaticResource markup extension. But what happens if we replace a specific resource? Would that be reflected in all objects using the resource? And if not, can we bind to the resource dynamically?

Getting ready

Make a copy of the previous recipe project CH02.SimpleResources, or create a new project named CH02.DynamicVsStatic and copy the Window XAML contents from the previous project to the new one.

How to do it...

We'll replace StaticResource with DynamicResource and see the effect:

  1. Open MainWindow.xaml. Add a button to the end of the StackPanel labeled Replace brush and connect it to an event handler named OnReplaceBrush. This is the added markup:

        <Button Content="Replace brush" 
           Click="OnReplaceBrush" />
  2. In the event handler, we'll replace the brush resource named brush1 with a completely new brush:

    void OnReplaceBrush(object...

Using user-selected colors and fonts


Sometimes it's useful to use one of the selected colors or fonts the user has chosen in the Windows Control Panel Personalization applet (or the older Display Settings in Windows XP), such as Window caption, Desktop color, and Selection color. Furthermore, an application may want to react dynamically to changes in those values. This can be achieved by accessing special resource keys within the SystemColors and SystemFonts classes.

Getting ready

Make sure Visual Studio is up and running. Go to the Control Panel Personalization applet and change the theme to Classic. This will make it easy to see the dynamic changes when colors of fonts change.

How to do it...

We'll create an application that uses some user-selected color and font, and reacts automaticaly to changes in those:

  1. Create a new WPF Application named CH02.UserSelectedColorsFonts.

  2. Open MainWindow.xaml. Add two rows to the grid.

  3. Add a Rectangle covering the first row and a TextBlock in the lower row...

Using binary resources


Binary resources are just that: chunks of bytes that typically mean something to the application, such as image or font files. In this recipe, we'll cover the basics of adding and using a binary resource.

Getting ready

Make sure Visual Studio is up and running.

How to do it...

We'll create a simple application that uses an image file added as a binary resource:

  1. Create a new WPF Application named CH02.BinaryResources.

  2. Let's add a logical images folder to the project. Right-click the project node in Solution Explorer, and select Add | New Folder.

  3. The folder is created as NewFolder1. Change its name to Images.

  4. Right-click on the newly created Images folder, and select Add | Existing Item…:

  5. Navigate to some image file on your system (don't forget to change the file type filter to Image files at the bottom of the open file dialog box). I've used apple.png (found in the downloadable source for this chapter), but any image will do, preferably no larger than 48 x 48 pixels. The solution...

Accessing binary resources in code


Accessing a binary resource in XAML is pretty straightforward, but this works for standard resources such as images. Other types of resources may be used in code, and this requires a different approach.

Getting ready

Make sure Visual Studio is up and running.

How to do it...

We'll create an application that shows book information read programmatically from an XML file stored as a resource:

  1. Create a new WPF Application named CH02.BinaryResourcesInCode.

  2. Add the books.xml (found in the downloadable source for this chapter) file as a resource (make sure Build Action is set to Resource). As an alternative, you can create the file yourself and type its contents as shown in the next step.

  3. The books.xml file looks something like the following:

    <Books>
       <Book Name="Windows Internals" Author="Mark Russinovich" />
       <Book Name="Essential COM" Author="Don Box" />
       <Book Name="Programming Windows with MFC" 
             Author="Jeff Prosise" />
    &lt...

Accessing binary resources from another assembly


Sometimes binary resources are defined in one assembly (typically a class library), but are needed in another assembly (another class library or an executable). WPF provides a uniform and consistent way of accessing these resources using the pack URI scheme. Let's see how to do this.

Getting ready

Make sure Visual Studio is up and running.

How to do it...

We'll create two assemblies—one that holds resources, and another that needs to use those resources:

  1. Create a new blank solution by selecting File | New Project from the main menu and then navigating to Other Project Types | Visual Studio Solutions. Name it BinaryResourceAccess:

  2. Right-click on the Solution node in Solution explorer, and select Add | New Project…:

  3. Select a WPF User Control Library project and name it CH02.ClassLibraryResources:

  4. We're not going to actually use any user controls, but this is a simple way to create a class library with WPF references already included.

  5. Delete the UserControl1...

Managing logical resources


Logical resources may be of various types, such as brushes, geometries, styles, and templates. Placing all those resources in a single file such as App.xaml hinders maintainability. A better approach would be to separate resources of different types (or based on some other criteria) to their own files. Still, they must be referenced somehow from within a common file such as App.xaml so they are recognized. This recipe shows how to do just that.

Getting ready

Make sure Visual Studio is up and running.

How to do it...

We'll create an application that separates its resources across multiple files for convenience and manageability:

  1. Create a new WPF Application named CH02.ManagingResources.

  2. We want to create a separate file that would hold (for example) brush resources. Right-click on the Project node in Solution explorer and select Add | ResourceDictionary…:

  3. In the Name box, type Brushes.xaml and click on Add.

  4. A XAML editor is opened with a ResourceDictionary as a root elementVisual...

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 ₱260 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 ₱260 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 9,542.97
Windows Presentation Foundation 4.5 Cookbook
₱3367.99
MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF
₱2806.99
Windows Presentation Foundation Development Cookbook
₱3367.99
Total 9,542.97 Stars icon
Banner background image

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.