Archive for the ‘Code Snippets’ Category

A Few Good Metadata Options for Silverlight

Saturday, May 8th, 2010

I’d like to highlight one more feature that is available in Silverlight if you use my code snippets.

Those who watched the value coercion video might have glimpsed the following enum within the FrameworkPropertyMetadata.cs code file:

public enum FrameworkPropertyMetadataOptions : int
    None = 0x0,
    AffectsMeasure = 0x1,
    AffectsArrange = 0x2,
    AffectsParentMeasure = 0x4,
    AffectsParentArrange = 0x8,

This enum provides a limited subset of the metadata options that are available in WPF.  Specifically, these are the options used with dependency properties that affect layout.

How do metadata options work?

If you are not familiar with these metadata options, here’s a quick rundown…  In WPF, a dependency property on a framework element can be registered with one or more metadata options.  This is done by combining the desired flags using a bitwise “OR” and then passing that value into the appropriate DependencyProperty.Register() overload.

As an example, the Width property on FrameworkElement is registered with the AffectsMeasure option.  As such, the property engine will take care of invalidating measure on the target element whenever the Width property changes.

The other layout options work pretty much the same way.  The AffectsArrange flag will cause InvalidateArrange() to be called on the target element when the property changes.  The AffectsParentMeasure and AffectsParentArrange flags will cause InvalidateMeasure() and InvalidateArrange() to be called, respectively, on the target element’s parent.

It’s All About Portability

In Silverlight, there is no native mechanism for registering a property to affect measure or arrange.  As such, you typically register a PropertyChangedCallback on the property and then explicitly call InvalidateMeasure() and/or InvalidateArrange() within your callback. 

If you use my snippets, you can follow the exact same approach in Silverlight that you would use in WPF for properties that affect layout. My FrameworkPropertyMetadata class will take care of the necessary layout invalidations.  So a property that affects measure could be declared in Silverlight using my ‘dp s1’ snippet, as follows:

#region VerticalExtent

/// <summary>
/// VerticalExtent Dependency Property
/// </summary>
public static readonly DependencyProperty VerticalExtentProperty =
    DependencyProperty.Register("VerticalExtent", typeof(double), typeof(MyControl),
        new FrameworkPropertyMetadata(double.NaN,

/// <summary>
/// Gets or sets the VerticalExtent property. This dependency property
/// indicates the vertical extent of the control.
/// </summary>
public double VerticalExtent
    get { return (double)GetValue(VerticalExtentProperty); }
    set { SetValue(VerticalExtentProperty, value); }


What about the other WPF metadata options?

There are several metadata options in WPF that are not included in my Silverlight enum.  These are intentionally excluded because they either cannot be supported outside the native Silverlight framework (e.g., the property engine would need to be modified to support the NotDataBindable option) or they simply don’t make sense in Silverlight (e.g., Silverlight does not currently support direct rendering via an OnRender() override, so I don’t provide an AffectsRender flag).

I hope you find the provided layout metadata options handy!


Value Coercion for the Masses

Wednesday, May 5th, 2010

My latest snippets package adds value coercion support to Silverlight dependency properties. The mechanism for coercing values is identical to the CoerceValueCallback approach used in WPF.

What is value coercion?

If you are not familiar with value coercion, it is simply a mechanism by which related (or “interdependent”) dependency properties can be kept in sync and valid.

The quintessential example can be found within the Slider control. A Slider has both Minimum and Maximum properties. Clearly, it would be a problem if the Maximum value were allowed to fall below the Minimum value. Value coercion is used to prevent this invalid state from occuring.

In WPF, the Slider control (or more specifically, the RangeBase control) ensures that these property values stay valid by using a feature of the dependency property metadata called a CoerceValueCallback. Whenever the Maximum property value changes, it is passed through this coercion function. If the Maximum value happens to be less than the Minimum value, the function will coerce it to be equal to the Minimum value so that it is valid.

The coercion routine for the Maximum property looks something like this:

private static object CoerceMaximum(DependencyObject d,
    object value)
    double min = ((RangeBase)d).Minimum;
    double max = (double)value;
    if (max < min) return min;
    return value;

Whenever the related Minimum property changes, the control explicitly coerces the Maximum property. This ensures that the Maximum value stays valid with respect to the new Minimum value.

The property changed callback for the Minimum property looks similar to this:

private static void OnMinimumChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)

Notice that changes to the Minimum property also result in coercion of the Slider’s Value property. That’s because the Value property also needs to stay valid. More specifically, it must be kept between the Minimum and Maximum values. That means if either the Minimum or Maximum values change, the Value property must explicitly be coerced. As such, the property changed callback for the Maximum property also coerces the Value property, something like this:

private static void OnMaximumChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)

Clearly, the Value property needs its own coercion routine to keep it between Minimum and Maximum. For completeness, here is what the CoerceValueCallback for the Value property looks like:

private static object CoerceValue(DependencyObject d,
    object value)
    double min = ((RangeBase)d).Minimum;
    double max = ((RangeBase)d).Maximum;
    double val = (double)value;
    if (val < min) return min;
    if (val > max) return max;
    return value;

Base Value vs. Effective Value

It is important to recognize that with value coercion, a dependency property has both a “base” (or “desired”) value and an “effective” (or “coerced”) value. The “base” value is always passed into the CoerceValueCallback and the value returned from that method becomes the new “effective” value.

In the case of the Minimum and Maximum example, if the “base” value of the Maximum property is less than the Minimum value, then the “effective” value of the Maximum property becomes equal to the Minimum value. Otherwise, the “base” and “effective” values are simply equal.

Value Coercion is Not Natively Supported in Silverlight

There’s nothing more frustrating than needing to port something from WPF to Silverlight and realizing that a key feature like value coercion does not yet exist in Silverlight. (For the record, I have no idea whether it will ever be supported natively, but if you use the mechanism provided by my snippets, you should be in great shape if/when we get true native support for value coercion in Silverlight.)

The lack of support for value coercion in Silverlight means you must roll a “do-it-yourself” version of the feature in your classes. The Silverlight Slider control attempts to do this. Unfortunately, this can lead to code that is cumbersome to maintain, especially if you need to use the same mechanism in several different classes.

Furthermore, achieving parity between frameworks can prove to be very difficult. As evidence of this, note that the pseudo-coercion within Silverlight’s native Slider control is just wrong. The Minimum property coerces the Value property upward, but does not coerce it back down correctly (and it’s likewise wrong for the Maximum property).

Value Coercion — There’s a Snippet for That!

To support value coercion in a consistent manner across your Silverlight classes, you can leverage my FrameworkPropertyMetadata class and the related SilverlightCoercionHelper class. Simply add a class file to your project called FrameworkPropertyMetadata.cs and then expand the “dp shc” snippet (Dependency Property — Silverlight Helper Classes) within it.

Whenever you declare a dependency property with a CoerceValueCallback (e.g., the “dp s3” snippet), you also need to initialize the owner type for value coercion and add a CoerceValue method to the class. To do this, expand the “dp scm” snippet (Dependency Property — Silverlight Coercion Methods) within your class.

To see a demonstration of the snippets in action, check out the video at the end of this post.

Cross-Framework Compatibility

If you use my snippets to support value coercion in Silverlight, your code should also compile just fine in WPF. When compiled in WPF, the framework’s native coercion mechanism will be used.

To support this cross-framework compatibility, you will notice that the helper classes and coercion methods in my snippets wrap certain code blocks within the #IF SILVERLIGHT directive.

Video Introduction to Value Coercion

I’ve put together a 14-minute screencast demonstrating all of this. Specifically, this video illustrates how value coercion works within the WPF and Silverlight native Slider controls. It then shows how to use my snippets to create similar interdependent Minimum, Maximum, and Value properties in a custom Silverlight control.

NOTE: The audio in this video has been “coerced” to protect the guilty! 😉

You can download the source code here for the Silverlight 4 sample coercion application created within the video.

I hope this helps a few folks maintain portable WPF/Silverlight code! 🙂


Updated Code Snippets for WPF and Silverlight

Friday, April 30th, 2010

I originally posted my Visual Studio WPF code snippets back in November of 2007. At that time, I was actually on the road delivering training for Silverlight 1.0. My co-instructor observed me using the snippets and suggested that I make them publicly available. It turned out to be a good suggestion, as I’ve received great feedback on the snippets over the last few years. Hopefully they’ve helped a few of you gain some productivity too. 🙂

We’ve definitely come a long ways since the days of SL 1.0 and javascript! My snippets have evolved over the years to better meet the needs of both WPF and Silverlight. An update is long overdue, so I’ve now posted the latest version of my snippets online…


Download the Snippets Here


Pick Your Language

As before, the installer package contains both C# and VB versions of each snippet. If you double click the .vsi file, you can choose exactly which snippets to install.

For those of you working in C#, you only have to remember a handful of shortcuts to access any of the 86 unique snippets:

  • dp (for dependency properties)
  • inpc (for an implementation of INotifyPropertyChanged)
  • op (for observable properties)
  • rc (for routed commands)
  • re (for routed events)

For those of you who work in VB, well… you have my sympathies! Just kidding. 😉 I would suggest using the snippet picker until you learn the shortcuts for the particular snippets that you find most helpful.

Pick Your Framework

Although my (self-endowed) doctoral degree is in WPF, I also spend a good amount of time writing Silverlight code. This latest snippet package brings my Silverlight snippets in line with my WPF snippets. For example, all 6 variations of dependency property declarations are now fully supported for SL 3 and SL 4. In C#, you can quickly access the dependency property snippets for Silverlight by typing ‘dp’, hitting Tab twice, and then typing ‘s’. You should see something like the following:

Silverlight Snippets

In addition to declaring DPs, I also use the ‘inpc’ and ‘op’ snippets quite heavily in Silverlight.

The ‘rc’ and ‘re’ (routed commands and routed events) snippets are mostly for WPF. However, the ‘re c’ snippets are very useful for declaring custom event args even in Silverlight. Just remember to hit delete when you tab to the “Routed” field in the snippet. There is also an ‘re s’ snippet that I use in Silverlight when I need to provide a property changed event. Note that the event it provides is not truly routed, as SL does not allow you to insert custom events into its routed pipeline. Still, it is often the appropriate choice when you want to create cross-framework code.

What changed?

Aside from the addition of about 20 new snippets, there were also a few improvements to the older snippets.  If you are using an earlier release, you may notice a few of these changes.  Probably the biggest difference is in the following method signature (found in many DP snippets):

Old Snippet

/// <summary>
/// Provides derived classes an opportunity to handle changes
/// to the Whatever property.
/// </summary>
protected virtual void OnWhateverChanged(DependencyPropertyChangedEventArgs e)

New and Improved Snippet

/// <summary>
/// Provides derived classes an opportunity to handle changes 
/// to the Whatever property.
/// </summary>
protected virtual void OnWhateverChanged(double oldValue, double newValue)

Without going into the mundane details, I’ll just say that the motivation for changing this signature on the WPF snippets was mostly code portability between WPF and Silverlight.  The former signature did not always work well because Silverlight does not provide a public constructor for DependencyPropertyChangedEventArgs.  This became problematic in coercion scenarios.  I also prefer the latter version because it provides a type-specific OnChanged callback, but that’s just a personal preference.

Are the old snippets still available?

For the luddites who are not ready for these modernized snippets, you can still download the older snippets here. 😉

For everyone else, I hope you like the new snippets!  There are a few gems in there which I’ll expound upon further in future posts.

My WPF Code Snippets… now available for Visual Basic

Monday, September 22nd, 2008

I first published my C# WPF code snippets last December in this post.  Due to increasing demand for VB versions of these snippets, I spent this past weekend porting them to VB.  They are now available for both languages. You can download the snippet installer here.

Updated October 1, 2008: 

I just updated the snippets to play nicely with the Strict option in VB.  Grab the latest installer to get a version of the VB snippets that properly casts the result of the CLR get accessors based on the DP type.

All 65 snippets are supported in both C# and VB.NET now.  The shortcuts for the VB versions are slightly different because the VB code editor does not provide the same level of support for snippets as the C# editor  (see rant below). 

In VB, for example, you cannot just type "dp" and hit tab twice to get a list of my dependency property snippets.  Instead, you must type the entire unique shortcut (e.g., "dp2") and then hit tab to expand that specific snippet.  It is probably easier to install all of the snippets within a single category (like "My Code Snippets") and then select the desired snippet from a list, as shown here:

I hope the VB snippets are helpful to a few of you!  Let me know if you find any problems with the ported code.


Small Rant Regarding VB Snippet Support

In my earlier post, I talked about how I am looking forward to a day when Visual Studio code snippets will support more advanced macro-like functionality.  After spending some time working with snippets in VB, I realize just how lucky I am to work primarily in C#.  On a scale of Classic Pong to XBox 360, the C# snippet support is probably somewhere around a PS2, whereas the VB.NET snippet support is barely a Nintendo 64!

Come on, Microsoft…  show a little love for that monster base of VB developers you created in the 90’s!  At a minimum, at least give them snippet parity with C#.  Here are a few of my complaints:

  • Intellisense should provide snippet hints.
  • The user should not have to tab through every field in the snippet… just the unique fields.
  • There should be support for functions like ClassName().
  • The $end$ tag should be supported.
  • Pressing ‘Enter’ should take the snippet out of edit mode and place the cursor at the $end$ tag.
  • If there are multiple snippets with the same shortcut, typing the shortcut should provide a filtered list of descriptions for the matching snippets.

Okay, I’m sure most VB developers know how to deal with all these limitations, and since I’m not really part of that constituency, my voice probably doesn’t hold much sway in this argument…  so I’m done now.  Enjoy the snippets!

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!