Archive for November, 2007

My WPF Code Snippets

Saturday, November 17th, 2007

Yikes!  Has it really been over a month since my last blog entry!?!

Okay, the last 6 weeks are a bit hazy and I wish I could blame my absence from the WPF Forum (and this blog) on something exciting, but honestly, it’s just been work.  A number of projects all converged at once creating “the perfect storm” of work engagements.  And although I love writing WPF code, I’m now hoping for a small respite from the daily deadlines.  Hopefully, the next few weeks will be a little more tame and I will be able to catch up with life in the WPF community.

Whenever we go through these crunch times, I realize how much I’ve come to depend upon the code snippet support in Visual Studio 2005/2008/2010.  I totally rely on my WPF code snippets… and its not just because of the time they save me writing code, but also because of the consistency they bring to my code.  I can look at any WPF classes I’ve written over the past few years and immediately understand what is going on in the properties, events, and commands exposed by those classes.

If you do not yet have a good set of Visual Studio code snippets, I would encourage you to develop them.  I have posted my C# WPF snippets here for anyone who is interested in perusing, adopting, or improving them.  🙂


January 4, 2008:  The downloadable snippets file now contains a .vsi file that can be used to directly import these snippets into Visual Studio 2005/2008/2010.  (Special thanks to the coworker who was nice enough to create the install package for me!)


(Apologies to the VB.NET WPF developers out there…  I have never ported these to VB, as the time I spend writing VB code is extremely limited.  But if anyone is up for a challenge and wants to port these and send them my way, I’d be happy to post the equivalent VB snippets on my site.)


September 22, 2008:  I finally got around to porting these snippets to VB.  See this post for the details.


I have designed these snippets to cover 98% of the usage scenarios that I encounter in a typical WPF development project.  I have also designed them to enforce good coding patterns, especially around consistency and documentation.

I won’t spend a lot of time explaining how to use them (because hopefully they are self-explanatory for WPF developers).  There are really only three shortcut keywords to remember:

  • dp  (for dependency properties)
  • rc  (for routed commands)
  • re  (for routed events)

From there, it’s just a matter of choosing the correct snippets from the context menu.  I’ve found that I can now invoke most of my snippets without even thinking about the keystrokes… my fingers just go into “auto” mode ( d – p – <tab> – <tab> – 2 – <enter> – property name – property type – … ). 

Of course, I created the blasted things, so maybe I’m not a representative sample.  😉

In addition to the framework-specific snippets, I’ve included a few other snippets in this zip that I also use quite a bit in WPF projects… “inpc” provides an implementation of the INotifyPropertyChanged interface and “op” is used to define observable properties that raise change notifications.

For Silverlight developers, note that I use these same snippets for Silverlight projects.  Well really, it’s just a few key snippets… namely, “inpc”, “op”, and “dp”.  You will want to use variation 2 of the dependency property snippets (both standard and attached properties).  Just remember that Silverlight uses PropertyMetadata rather than FrameworkPropertyMetadata, so hit delete when you tab to that field in the snippet. 🙂

I’m looking forward to a day when I’ll be able to do more advanced things in my snippets (custom functions, custom formatting, capitalization, custom placement for different code parts, etc).  In the meantime, I hope others will find my existing snippets useful!


Can I borrow that DP for a little while?

Wednesday, November 14th, 2007

If you’re like me, you sometimes want to prove out a concept in XAML before implementing the “real” solution.  For example, you may want to create a new control which is very similar to an existing control, but lacking a property or two.  Rather than derive the control from a base class and add the new properties, it might be nice to simply re-template the existing control and pretend that it has the necessary properties.

Luckily, WPF makes this fairly easy through its support for attached properties.  It’s very likely that the framework has already defined a couple of properties of the very type you are needing.  If you cannot find an exact match, you can usually find something close enough.

Anyone who follows my posts in the WPF forum knows that I’m a big fan of “borrowing” attached properties from the framework.  This is especially useful in the forum because it allows me to provide a XamlPad-ready solution to demonstrate a concept.  Here are a couple of examples:

Over the years, I have assembled a catalog that includes most of the framework-defined, public attached DPs (yes, I’ve spent far too many hours in reflector and writing code that greps the framework :P), as well as all of the relevant information about those DPs.  For anyone who is similarly inclined to “borrow” from the framework, here is my spreadsheet of attached DPs.

A few words of caution… 

  • You should always know what the owner class does with any property you borrow.
  • You should pay attention to default values and inheritance.  Sometimes you need a bool property with a default value of true… other times you may want a default value of false.  Sometimes you need a property that inherits… other times you explicitly don’t want inheritance.  (Borrowing a property like TextElement.FontSize could really screw up things lower in the tree.)
  • The owner class may sometimes define a PropertyChangedCallback that will interfere with your ability to use the property as you wish.  Always know what the owner class does with the property.
  • The owner class may provide a validation routine for the property that prevents you from entering the value you want to specify.  Again, always know what the owner class does with the property.
  • The property may be registered in a manner that makes it costly perf-wise, such as FixedPage.Bottom which invalidates the parent’s arrange anytime the property changes on an object.  Sometimes you may explicitly want this behavior… other times it will just unnecessarily cause layout passes.  Again, always know what the owner class does with the property.
  • If you use a property in a scenario where the framework itself is trying to use the property (such as TextSearch.TextPath on an ItemsControl), you are liable to find yourself in contention with the framework.

Okay, I’m sure I could go on, but you get the general idea.

The nice thing about this spreadsheet is that it has all of the information you might want to know about the properties, including the following:

  • Defining Class / Owner Type
  • Property Name
  • Type
  • Metadata Type
  • Default Value
  • Owner Handles Changes (the owner registered a PropertyChangedCallback)
  • Coerced (the owner coerces the value)
  • Validation (the owner validates the value)
  • Inherits
  • Metadata Options

It also contains a second worksheet with a pivot table that can be used to easily filter the properties down to exactly those that meet your needs.  And remember, if you can’t find a property that matches the exact type you’re looking for, you can usually just use a DP of type string because there are type converters for most objects that are capable of translating to/from string values.  And there are a few properties of type ‘object’ that can serve as uber-utility DPs.

Let the borrowing begin!

A trigger for the MenuItem directly under the mouse (deja vu)

Tuesday, November 6th, 2007

By (indirect) request, I have put together a helper class that provides a property that can be used as a trigger to determine if a MenuItem is directly under the mouse.  This is analogous to this solution offered by Mike Hillberg for dealing with the TreeViewItem directly under the mouse. 

Mike does a good job of explaining the general problem and solution, so I highly recommend that you read his post!

The MenuItem scenario has its own set of issues to overcome, most of which arise from the fact that submenu items are very often disabled (due to application state).  Things are further complicated by the fact that the subitems are presented within a Popup.  I will leave it as an exercise for the reader to review my approach to see how I dealt with these issues (because I’m just too lazy to explain myself right now ;)).

Here is the code for the MenuHelper class (open source, as always) and here is a sample app that demonstrates its usage.  Note that the sample class randomly disables menu items to simulate the changing state of an application.

Hope this is useful.  Let me know if you encounter any issues with the helper class.


ItemsControl: 'C' is for Collection

Monday, November 5th, 2007

The series continues…

An ItemsControl would be nothing without its collection of Items. In this post, we investigate the “Items” of an ItemsControl, looking at each of the following areas:

If I were rating the technical level of each post in this series, I would put this particular post somewhere in the range of moderate to advanced (but still very approachable :)).

The Items Collection (a.k.a, the ItemCollection)

The “Items” property of an ItemsControl provides access to a collection of objects, or data items, that make up the logical content of the control. The type of this property is ItemCollection. (I will use the terms “Items collection” and “ItemCollection” interchangeably.) The “Type” of each item within the Items collection is Object. So literally any CLR object can be added to an ItemCollection.

We will look at the ItemCollection class, itself, in more detail momentarily, but first, there are a couple of things to note about the Items property declaration on ItemsControl.

1) The Items property is a read-only CLR property.

This means that the collection exposed via the Items property must be instantiated by the control itself. In fact, the ItemCollection class does not even provide a public constructor.

2) The Items property is not backed by a dependency property.

This means that you cannot set a binding directly on the Items property. However, you can definitely bind an ItemsControl to a collection of items. We will look at how this works shortly, but before we do, we should look at the simpler, non-databound (or direct) scenario…

ItemCollection Modes: Direct and ItemsSource

Although the Items property is read only, the provided collection is not necessarily read only. In fact, in earlier posts, we’ve already seen that you can directly add items to an ItemsControl:

  <sys:String>Item 1</sys:String>
  <sys:String>Item 2</sys:String>
  <sys:String>Item 3</sys:String>

Because items are added directly to the ListBox, this is an example of using an ItemCollection in “direct mode”. This is by far the simplest mode to use conceptually. In direct mode, the ItemCollection class works exactly like every other .NET collection. You can directly access all of the expected members of an indexed collection: Add(), Insert(), Remove(), RemoveAt(), IndexOf(), Items[index], Count, etc.

The other mode for an ItemCollection is called “ItemsSource mode”. In ItemsSource mode, the items in the ItemCollection correspond to items in a source collection. That source collection is specified via a separate property on the ItemsControl that is appropriately named “ItemsSource”.

The following shows a typical scenario of an ItemsControl using ItemsSource mode:

<ListView ItemsSource="{Binding Path=Characters}">
      <GridViewColumn Width="100"
        DisplayMemberBinding="{Binding Last}"
        Header="Last Name" />
      <GridViewColumn Width="100"
        DisplayMemberBinding="{Binding First}"
        Header="First Name" />
      <GridViewColumn Width="60"
        DisplayMemberBinding="{Binding Gender}"
        Header="Gender" />

The ItemsSource property is a dependency property of type IEnumerable. This tells us two important things:

1) The source collection can be any enumerable collection.

2) The ItemsSource property can be established using a binding.

As such, it is the ItemsSource property (in conjunction with the ItemsSource mode of an ItemCollection) that enables an ItemsControl to be databound to a collection.

Sidenote: Although you will most often see the ItemsSource property of an ItemsControl set via a binding, there is no reason that the ItemsSource property cannot be directly set to an enumerable collection, as shown here:

<ListBox ItemsSource="{StaticResource Characters}" />

The Modes are Mutually Exclusive

It should be noted that direct mode and ItemsSource mode are mutually exclusive. An ItemCollection is either in direct mode or in ItemsSource mode, but never both.

Once Items have been explicitly added to the Items collection, it is in direct mode. A subsequent attempt to set the ItemsSource property after entering direct mode will result in an exception.

Similarly, once the ItemsSource property has been set, the Items collection is in ItemsSource mode. A subsequent attempt to directly modify the Items collection (using Add(), Insert(), Remove(), etc) will result in an exception.

The only way to change modes at runtime is to either 1) clear the Items collection via the Clear method (if in direct mode) prior to setting the ItemsSource property, or 2) set the ItemsSource property to null (if in ItemsSource mode) prior to calling the direct access methods of ItemCollection.

Observable Collections Support Dynamic Updates

As noted earlier, in direct mode, changes to the Items collection are made through direct access methods of the ItemCollection class. Any such direct changes made at runtime will cause the visuals to be updated immediately.

But what about dynamic collection changes in ItemsSource mode? How could the Items collection possibly know about changes to the source collection?

The answer is that the ItemCollection cannot know about any such changes unless the source collection chooses to announce those changes by providing change notifications. The way a source collection does this is by fully implementing and supporting the INotifyCollectionChanged interface. Any collection that provides these change notifications is said to be observable.

Dynamic changes to an observable collection will be immediately reflected in the Items collection of any ItemsControl that is bound to the collection. Consequently, these changes will be immediately reflected in the user interface.

The INotifyCollectionChanged interface is not super complex, but ensuring proper implementation does place an extra burden on the source collection. If developers had to implement this interface anytime they wanted to bind to a collection, it would be a huge inconvenience. Luckily, the .NET framework provides a very handy generic template class called ObservableCollection<T>. By creating an instance of this class, you automatically get all of the change notifications without having to do any extra work.

Typically, you will see a collection class derive from ObservableCollection<T>, to create a strongly typed collection, as follows:

    public class StringCollection : ObservableCollection<string>

Any instance of this StringCollection class is fully observable and will serve well as the ItemsSource of an ItemsControl. It can be used exactly like an instance of Collection<string>.

So what if the collection is not observable? Can it still serve as an ItemsSource?

Absolutely. As noted earlier, any enumerable collection can serve as the source of an Items collection. The only caveat is that the Items collection will not be updated dynamically if the source collection changes at runtime. Rather, the collection will be enumerated once and its members will be added to the Items collection when the ItemsSource property is first established. Thereafter, if you want the Items collection to be updated, you must explicitly call the Refresh() method of ItemCollection.

CollectionView: “The Great Equalizer”

If you’ve worked with ItemsControl much, you probably know that sorting, grouping, and filtering are supported via the CollectionView class. This class also supports the notion of currency, which means a CollectionView maintains a current item pointer that can be accessed and moved using methods on the CollectionView.

Every enumerable collection in WPF has a default view. The collection may have multiple other views, each with its own sorting, grouping, and filtering parameters. A common way to establish a view of a collection in markup is to leverage the CollectionViewSource class, as shown here:

<CollectionViewSource x:Key="characterView"
    Source="{StaticResource Characters} ">
    <componentModel:SortDescription PropertyName="First" />
    <dat:PropertyGroupDescription PropertyName="Last" />

This CollectionViewSource can then be specified as the ItemsSource of an ItemsControl, thereby causing its associated view of the collection to serve as the CollectionView for the control.

“But Dad, I don’t WANT a CollectionView!”

“I didn’t ask what you WANT… As long as you’re living under my roof, you’ll use a CollectionView!”

With WPF, sometimes it’s not as much about what you want, as it is about what the framework needs. The CollectionView class is a classic example. When it comes to binding controls to a collection of data items, the framework needs a way to treat all collections in a consistent manner.

Unfortunately, not all enumerable collections were created equal. For example, IList provides direct index-based access to items, whereas IEnumerable requires that you enumerate all items starting from the beginning of the collection until you come to the index you care about. For another example, consider a collection class that supports the INotifyCollectionChanged interface to provide collection change notifications versus a simple Collection<T> class that provides no such notifications.

The framework architects wanted to support binding to as many different types of collections as possible. But imagine how ugly the code for the ItemsControl class would be if it had to account for differences among collection types with conditional code blocks… if it’s an observable collection, do this, or if it’s an IList, do this, or if it’s an IEnumerable, do this, etc.

Enter the CollectionView class…

To deal with this challenge of disparate collections, WPF introduces the CollectionView class to serve as the great equalizer of enumerable collections. It is the CollectionView class that internally looks at a collection’s supported interfaces and determines how best to deal with the collection. It then surfaces a view of the collection through a well-defined set of properties, methods, and events. Essentially, it allows all collections to be treated by the ItemsControl class as equals.

So whether or not you care about currency, grouping, sorting, filtering, change notifications, etc., the Items collection of an ItemsControl is always maintained internally using a CollectionView. In fact, the ItemCollection class is a CollectionView.

Although true, that last statement is a little misleading since really, ItemCollection is just a wrapper class for an internal CollectionView member. The type of the internal CollectionView is determined by the type of the source collection and the mode of the ItemCollection. In Direct mode, it is always of type InnerItemCollectionView (an internal class designed specifically for direct mode views). In ItemsSource mode, it will be of type CollectionView for an IEnumerable source, ListCollectionView for an IList source, or BindingListCollectionView for an IBindingList or IBindingListView source.

So you’re observable… Who cares?

CollectionView does. We’ve already noted that dynamic changes to observable collections are immediately reflected in the Items collection. It is the CollectionView class that actually listens to the events raised by the collection. So if you’ve ever wondered exactly who is monitoring these events, get a life! Sorry… I meant to say, it’s CollectionView. Now you know.

Performance Considerations around Bound Collections

Keeping in mind that CollectionView serves as the great equalizer of collections, we should look at some performance considerations around binding to collections. We’ve already acknowledged that not all collections support the same features. Often, CollectionView must perform extra work to support its common interface for collections.

One of the major features provided by CollectionView is indexing for an enumerable collection. That is, CollectionView provides direct access to members of the collection by an integer-based index. This means it must support properties like this[int index] and Count, as well as methods like Contains() and IndexOf().

If the source collection already supports indexing, you will see much better performance when binding to the collection. This means that the best candidates for a source collection are those that support the IList interface. It should be noted that ObservableCollection<T> implements IList, so it’s a great choice.

If the source collection does not support index-based access (ICollection or IEnumerable, for example), then CollectionView must do a lot more work to surface the view as an indexed collection. In order to support a property like Count, it may be necessary to enumerate the entire collection. And some methods like Contains(), IndexOf(), and GetItemAt() can be super expensive, since the performance of the algorithm to support these operations is directly proportional to the size of the collection.

So the key perf takeaway is that the source collection should support IList whenever possible.

Items and the Element Trees

The items within the Items collection make up the logical children of the ItemsControl. They are said to be members of the logical tree. For a HeaderedItemsControl, the headers associated with each item will also be logical children of the ItemsControl. (Btw, if you’re not sure what a HeaderedItemsControl is, you should revisit The ICIQ Test and spend a little more time exploring the tooltips after receiving your score.)

If the items in the Items collection happen to be visuals, then they will also be members of the visual tree. If they are not visuals, they will instead be represented visually using an inflated template of visuals. Since the template represents data items, it is called a DataTemplate. For more on that, please tune in for the next episode in this series… ‘D’ is for DataTemplate.