Interesting thread on data binding

May 30, 2007

Yesterday I started a thread on the WPF Forum which has turned out to be rather interesting.  I won’t go into too much detail about it in this post, but here’s the general gist.  Normally the WPF data binding system requires a data object to send out notifications when one of its properties has changed so that the new value can be displayed in the UI.  There are three ways to do this:

  1. Raise a PropertyNameChanged event when a property has been changed (ex. Raise a NameChanged event when the Name property of an object is set).
  2. Implement INotifyPropertyChanged on the data object and raise its PropertyChanged event when a property is set to a new value.
  3. Derive the business object’s class from DependencyObject and implement the property as a dependency property.  DPs handle all of the change notification work for you.

As described on the thread I discovered an oddity where the new value of a property was appearing in the user interface, even though the data object emitted no property change notifications.  The answer to this mystery, as Douglas Stockwell figured out, has to do with the fact that the data binding system uses PropertyDescriptors to set the value of a property on the source object.  PropertyDescriptors have built-in value change notifications which they raise when setting a property on an object.  The binding system listens for change notifications sent out by PropertyDescriptors and, when they are raised, will update other Bindings which are bound to the same property on the source object.

For more information about this quirky, yet interesting, aspect of the WPF binding system check it out here.

WPF presentation in September

May 28, 2007

I have another WPF presentation scheduled.  On September 17th I will be speaking at VSLive! New York 2007.  If you plan on attending the conference and want to hear my one hour harangue about the wonders of WPF, be sure to drop on by.  I’ll be speaking at 10:30 AM.  Here’s a link to the .NET 3.0 Live! Track, which is what my presentation is part of:

As a reminder, I’ll also be speaking at the NYC .NET Developers Group in August.  Read more about it here:

Review of Essential WPF

May 27, 2007

Recently I purchased and voraciously read Chris Anderson’s book “Essential Windows Presentation Foundation.”  Shortly after cracking it open for the first time I realized that this is a book which every WPF developer must read.  I highly recommend it.

Anderson was one of the chief architects on the WPF team at Microsoft.  He was involved with many design iterations of the platform over the course of several years.  As a result, the depth and insight into the platform which his book offers is truly astounding.  He does not only explain what you can do with WPF, but explains why the features of the platform were designed the way they were. 

Anderson will even discuss how some features were initially conceived but why the initial design did not work well, and how the final design overcomes those problems.  For example, the styling system in WPF initially used a miniature query language to specify how a style should be applied to elements in a UI.  He explains the shortcomings of that model and why the styling system we are all familiar with is better. That is priceless information for anyone who is serious about understanding the Windows Presentation Foundation.

Toward the beginning of the book Anderson lists the three overarching principles behind the design of WPF: element composition, rich content everywhere, and a simple programming model.  Throughout the rest of the book he demonstrates how the various functional areas in the platform adhere to those guiding principles.  Looking at the platform from that perspective clarified a lot of things for me.   I found it especially interesting how he discusses the command model as a means of simplifying the programming model of a composition-based architecture. 

In my review of “Windows Presentation Foundation Unleashed” I stated that “I just can’t go back to reading black-and-white books about WPF.”  I guess I was wrong!  The images in “Essential Windows Presentation Foundation” are black-and-white, but it didn’t bother me one bit.  Anderson’s book is not done any injustice by black-and-white images.  The content of the book is so interesting, and well presented, that the images were not very important to me.

I have only one qualm with Anderson’s book.  I was hoping that it would have an in-depth explanation of the Media Integration Layer (MIL).  There still seems to be a big gaping hole in general around this topic, not only in Anderson’s book.  It would have been great if he really dove deep into how drawing instructions are sent to the render thread, how changes to the visual tree are communicated to the MIL representation of the UI, how this works in a remote desktop scenario, etc.  Unfortunately I guess I’ll have to wait for someone else to demystify that topic.

To recap, I think that “Essential Windows Presentation Foundation” is a must-read for WPF developers.  Take my word for it, just buy the book and start reading it.

A review of markup extensions

May 25, 2007

XAML is simple, which is a good thing.  It is just an XML-based language used to declare objects and the relationships between them.  One side effect of being simple is that it can be verbose.  This cumbersome verbosity was one of the main reasons why the concept of markup extensions was introduced.  A markup extension can be used to turn many lines of XAML into one concise expression, as we will see later on.

Another side effect of XAML’s simplicity is that it does not have any “built in” knowledge of common artifacts used by WPF or the CLR; such as resource references, data binding, a null value, arrays, static members of a class, etc.  Since XAML can be an integral part of application development there needs to be some way for developers to express those ideas in it.  This is another major reason why markup extensions were added to Microsoft’s implementation of XAML.

Here is an example of several markup extensions put to use (in this demo, the StackPanel’s DataContext was set in the code-behind to a Person object):

Markup extensions put to use

All markup extensions derive from the abstract MarkupExtension class and override its ProvideValue method.  The naming convention is to append the word Extension to the subclass’s name (only the Binding class does not follow the pattern). The XAML parser allows markup extensions to be created within {curly braces} and it also allows you to omit the Extension suffix when using a markup extension, if you want to. 

In the XAML above, take a look at the TextBox’s Text property, and the CheckBox’s IsChecked property.  They both use the Binding markup extension to bind their values to a property on the data context (a Person object).  The Binding associated with the TextBox’s Text property is much less verbose than the IsChecked Binding.  The verbosity reduction would be even greater if the Binding configuration was more elaborate. 

If you want to see what this ugly demo app looks like, click on the thumbnail image here:
Markup extensions demo UI

Here are several useful resources regarding markup extensions:

Markup Extensions and XAML

Creating a Simple MarkupExtension

Limited generics support in Xaml

2D physics in Silverlight 1.1

May 23, 2007

Chris Cavanagh, the man who came in second place in The WPF Challenge for his WPF Physics demo, is at it again.  This time he has built a Silverlight 1.1 app on top of a physics engine.  I’m amazed that Silverlight can handle this type of scenario!  As Chris points out in his blog post about the demo app, there seems to be some performance issues in Silverlight which cause the animations to “freeze” for a short time.  Other than that, the demo is very cool!  Check it out here:

WPF presentation in August

May 22, 2007

I will be speaking about WPF at the NYC .NET Developers Group meeting on August 16th, 2007.  If you live in or around New York City and would like to attend a free seminar about WPF, then be sure to stop by.  Here’s more info about my presentation:

 See you there! :D

IanG in 3D

May 19, 2007

I normally don’t like to create blog posts which just link off to things that other people have done, but this time is one of the exceptions.  Ian Griffiths created an amazingly cool demo of flippable 3D list items using nothing but XAML.  I am blown away!!  Check it out here:

Further demystification of dependency properties

May 17, 2007

In my previous blog post we examined how a dependency property can be given a value by multiple entities, but its actual value is resolved by the WPF property system based on a set of well-defined rules.  In this post we will dig deeper into how this works, by examining how a dependency property in a simple demo application gets its value.  Understanding how this value resolution process works is critical for those of us who want to do serious WPF programming, so I think it’s important to study this topic in great depth.

The demo application, which is available to download at the end of this post, contains a TextBlock whose Text property is set in various ways.  We can experiment with how the Text dependency property’s value is determined by checking/unchecking some CheckBoxs and putting the mouse cursor over the TextBlock (which activates a Trigger).

This is what the demo app looks like when you first start it:

Initial UI

The TextBlock whose Text property we are interested in is green.  In the screenshot above, it is displaying the string which was assigned to its Text property in the code-behind.

If you uncheck the upper CheckBox, the following method is executed:

ClearValue in action

The UI now looks like this:

Style-supplied value

Here is the Style which provides the TextBlock’s Text property with its new value:

Style applied to the TextBlock

If you were to now put the mouse cursor over the TextBlock, the Style’s sole trigger would be activated.  At that point the Setter in the Style’s Trigger would provide the property’s effective value. The UI would look like this:

Trigger-supplied value

If you were to then uncheck the bottom CheckBox, the Text property’s default value (an empty string) would be used. At that point the TextBlock is not displayed because a TextBlock naturally wants to only be big enough to display its text.  In this situation the UI looks like this:

The Text property’s default value is being used here

This demonstrates how a dependency property’s value is contingent on the values provided to it by external entities, such as a Style or default value.  In this example, when the Text property has a local value assigned to it, that value trumps those provided by the Style and the property’s default value.  When the Style’s trigger is active, its value takes precedence over the Style’s Setter and the property’s default value. 

You can download the demo project here.  Be sure to change the file’s extension from .DOC to .ZIP and then decompress it.

Demystifying dependency properties

May 16, 2007

There is something very important to know about dependency properties.  Once you understand this fundamental point, much of WPF becomes more intuitive.

The value of a dependency property is resolved. 

Normal CLR properties (i.e. not dependency properties) typically provide a getter and/or setter with which the value of a private field can be retrieved and/or modified.  When you set a normal CLR property, you might usually think of it as assigning a value to a field.  Usually whatever value you set a property to is the value which is returned when you access its getter.  Of course, properties can contain other logic which executes before and after the field is modified or returned.  That’s a major reason why they exist.

Dependency properties are a different animal altogether.  They never represent a private field in your class.  You can assign a DP a specific value, but that is not necessarily the value which will be returned when you access its getter.  Even if your DP has no validation or value coercion logic, you still might not get back the same value you put in. 

There is a well-defined set of rules which is used internally by WPF to figure out what the real value of a DP is.  Here is a brief summary of the rules of precedence used when resolving the value of a DP (read more about it here):

  1. Property system coercion
  2. Active animations, or animations with a Hold behavior
  3. Local value
  4. TemplatedParent template
  5. Style triggers
  6. Template triggers
  7. Style setters
  8. Theme style
  9. Inheritance
  10. Default value from dependency property metadata

As that list suggests, there is a lot more going on when the value of a DP is determined than simply using the value of a field.  When you explicitly set a DP to a value (ex. this.Height = 123;), you are assigning it a “local value.”  As you can see above, a DP’s local value is the third place the system will look when resolving the property’s value. 

If the DP was registered with a callback to coerce the value to which it is set, the value returned by the callback is returned the next time you access the property.  If the DP is being animated, or was animated by an Animation which “holds” its value after it completes, the Animation’s value is returned.  If neither of those conditions is met, the DP will resolve to the value which you assigned to the property (the local value).  Failing that, the DP resolution keeps walking down that list looking for an applicable value to use.  If it reaches the end of the list and discovers that the DP was not registered with a default value, then the property’s getter returns null or zero (which are the default values for a reference type or value type, respectively).

On a side note, this explains how a trigger is able to “magically” revert the value of a DP back to the original value, once the trigger is no longer active.  Since the value applied by a trigger is part of the value resolution algorithm, as soon as a trigger stops applying a value to a DP, the DP’s value is taken from somewhere further down the list.  The DP’s value is never actually reverted, because it does not have a value in the first place!

Remember, a DP never really “has” a value…its value depends on various external factors.  That’s why they are called dependency properties.

In my next post we take a look at an example of the DP value resolution process being used, to gain a clearer understanding of how it works.

A new way to implement template selectors

May 13, 2007

I just posted an article on CodeProject which shows a very flexible and powerful way to implement template selectors.  The technique involves a class I created called RoutedDataTemplateSelector.  The benefits of using this class are explained in the article, which can be found here:



Get every new post delivered to your Inbox.

Join 273 other followers