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
AU$24.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (30 Ratings)
Paperback Sep 2012 464 pages 1st Edition
eBook
AU$50.99 AU$72.99
Paperback
AU$90.99
Subscription
Free Trial
Renews at AU$24.99p/m
Arrow left icon
Profile Icon Pavel Yosifovich
Arrow right icon
AU$24.99 per month
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (30 Ratings)
Paperback Sep 2012 464 pages 1st Edition
eBook
AU$50.99 AU$72.99
Paperback
AU$90.99
Subscription
Free Trial
Renews at AU$24.99p/m
eBook
AU$50.99 AU$72.99
Paperback
AU$90.99
Subscription
Free Trial
Renews at AU$24.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $24.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781849686228
Vendor :
Microsoft
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $24.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
AU$24.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
AU$249.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 AU$5 each
Feature tick icon Exclusive print discounts
AU$349.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 AU$5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total AU$ 257.97
Windows Presentation Foundation 4.5 Cookbook
AU$90.99
MVVM Survival Guide for Enterprise Architectures in Silverlight and WPF
AU$75.99
Windows Presentation Foundation Development Cookbook
AU$90.99
Total AU$ 257.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.