Silverlight Code Snippets for DependencyProperties and other Handy Stuff

image

Download The Snippets Now (provided for the reading averse)

I was teaching someone about DependencyProperty the other day when I realized two things: first, DependencyProperty is a bad name.  Does anyone know what they depend on (DependencyObject doesn’t count)?  The dependency thing makes them sound kind of wimpy when, in fact, they’re actually awesome.  Going forward, you can use the terms DependencyProperty and SuperProperty interchangeably with me.

Second, I realized that there isn’t a good built in snippet for Silverlight DPs (or SPs). At least not one that I know of.  And without a snippet, whose going to bother to create a DP.  Seriously, it would be a pain.

I’m a snippet enthusiast or, dare I say, a fanatic.  It’s because I think that a good snippet library makes for good code: it makes your code consistent and it encourages you to do things the “right” way even if “right” requires a lot of code.

I’m such a snippet fan, in fact, that I devoted my talk at MIX last year to the subject.  Unfortunately, a lot of the snippets from the talk have grown stale.  In the meantime, I’ve been building out a new library.  For WPF, I use Dr. WPF’s indispensible snippets.  For Silverlight, I’ve slowly been building up a new library.  Since I haven’t been able to find much else out there, I thought I’d share mine.

Download The Snippets

If you’re new to VS snippets, you can get the skinny here.  To use them you just install the .vsi (see link above) and then type the snippet shortcut (e.g. sldp), hit tab a couple of times to kick off the snippet and then start providing the values it asks for (hit tab to move between values).  When you’re done, hit enter.

The Short Descriptions

Here’s the short guide to the snippets.  A little more detail follows.

sldp A basic Silverlight DependencyProperty
sldpc A Silverlight DependencyProperty with a property changed callback
sldpa An attached Silverlight Dependency Property
slevent A really basic event definition
slsbc An inline, anonymous Storyboard.Completed handler (check this one out, it’s cooler than it sounds)
slpanel A really simple implementation of a panel
slrss A super basic collection class that loads an RSS feed
slvc The boilerplate code you need to create a value converter

The Long Descriptions

sldp

This snippet creates the most basic DependencyProperty (i.e. SuperProperty) possible (well, most basic possible that is still useful).  You just specific the name, the type and the default value. Helfpul hint: remember that when you provide a default value for a double, you need to include the decimal (like in 0.0 instead of just 0) so that the compiler treats is like a double and not an int.

#region MyProperty (DependencyProperty)

/// <summary>
/// A description of the property.
/// </summary>
public int MyProperty
{
    get { return (int)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty =
    DependencyProperty.Register("MyProperty", typeof(int), typeof(Page),
      new PropertyMetadata(0));

#endregion

sldpc

This is a DependencyProperty that includes a a place to handle the associated property changed notifications (and a protected method in case subclasses also want to know about the change).

#region MyChangingProperty (DependencyProperty)

/// <summary>
/// A description of the property.
/// </summary>
public int MyChangingProperty
{
    get { return (int)GetValue(MyChangingPropertyProperty); }
    set { SetValue(MyChangingPropertyProperty, value); }
}
public static readonly DependencyProperty MyChangingPropertyProperty =
    DependencyProperty.Register("MyChangingProperty", typeof(int), typeof(Page),
    new PropertyMetadata(0, new PropertyChangedCallback(OnMyChangingPropertyChanged)));

private static void OnMyChangingPropertyChanged(DependencyObject d,
    DependencyPropertyChangedEventArgs e)
{
    ((Page)d).OnMyChangingPropertyChanged(e);
}

protected virtual void OnMyChangingPropertyChanged(DependencyPropertyChangedEventArgs e)
{
}

#endregion

sldpa

This is a snippet for an attached DependencyProperty.  That means that this value can be set on any element (e.g. Canvas.Left is an attached property defined by canvas to be set on other elements).  This also has property changed handler, but notice that its a static.  That’s because the change could happen on any object so you’ll want to pay attention to the DependencyObject that gets passed in to the handler.  That’s the object where the property was changed.

#region MyAttachedProperty (Attached DependencyProperty)

public static readonly DependencyProperty MyAttachedPropertyProperty =
    DependencyProperty.RegisterAttached("MyAttachedProperty", typeof(double), typeof(Page),
    new PropertyMetadata(new PropertyChangedCallback(OnMyAttachedPropertyChanged)));

public static void SetMyAttachedProperty(DependencyObject o, double value)
{
    o.SetValue(MyAttachedPropertyProperty, value);
}

public static double GetMyAttachedProperty(DependencyObject o)
{
    return (double)o.GetValue(MyAttachedPropertyProperty);
}

private static void OnMyAttachedPropertyChanged(DependencyObject o,
    DependencyPropertyChangedEventArgs e)
{

}

#endregion

slevent

This snippet creates a really simple event.  I use the RoutedEvent types even though (as far as I know) they aren’t actually routed.  There may be a better practice here, but this meets my needs 90% of the time.  Feel free to let me know if you have a better suggestion.

#region SomethingChanged

/// <summary>
/// A description of the event.
/// </summary>
public event RoutedEventHandler SomethingChanged;

private void RaiseSomethingChanged()
{
    if (SomethingChanged != null)
    {
        SomethingChanged(this, new RoutedEventArgs());
    }
}

#endregion

slsbc

This snippet creates an inline completed event handler for a storyboard using an anonymous delegate. I like this approach for handing completed events because it makes it straightforward to remove the handler (thanks to Dr. WPF for that suggestion) and it allows you to access local variables from within the handler.  I haven’t found a clean way to do either of those things any other way, so I end up writing most of my Storyboard event handlers this way.   By the way, the delegate has to be declared first like this so that we have a reference to it (to remove it) from within the handler.

// using an anonymous, inline handler for the completed event allows you to use 
// local variables from within the event handler and keeps our code cleaner

EventHandler handler = null;
handler = delegate(object s, EventArgs e)
{
    // remove the handler 
    MyStoryboard.Completed -= handler;

    // code to execute when the storyboard is completed goes here
};

MyStoryboard.Completed += handler;
MyStoryboard.Begin();

Note: The rest of these snippets are much longer so I’m not going to include them inline.  You’ll have to download them to check them out.

slpanel

This snippet creates an entire panel, including very very basic implementations of MeasureOverride and ArrangeOverride.  To be clear, this is not a robust panel implementation.  MeasureOverride, in particular, is not going to give you the results you probably want in advanced scenarios (like inside of a ScrollViewer).  But this will get you started.  It’s gets the boilerplate out of the way and lets you start partying on the layout logic really quickly.

slvc

This snippet creates a shell for a ValueConverter which you can use in conjunction with a binding to modify a value during the binding process.  It’s an entire class (like the panel) so you’ll want to make sure you use it in the right spot in your file.

slrss

This snippet creates a very simple collection out of the items in an RSS feed.  You provide the URL and this does the rest.  It’s a great way to quickly get up and running with a databinding scenario.  I mostly use this for training, etc.  It’s also a simple example of how to parse an XML feed using LINQ and how to load a file using the async web request stuff.  Oh, and it includes the content for a simple crossdomain.xml policy file.  It’s kind of a grab bag but I kept it around bits of it from time to time.

16 comments

 

[...] I’m a snippet enthusiast or, dare I say, a fanatic.  It’s because I think that a good snippet library makes for good code: it makes your code consistent and it encourages you to do things the “right” way even if “right” requires a lot of code. more from blog.nerdplusart.com [...]

 

Rubens

19 feb 2009

 

Hi this looks very useful – any chance you can post the snippets as a .snippet file? I don’t seem to be able to install the .vsi on Visual Studio Express…
Thanks!

 

Igor Ostrovsky

19 feb 2009

 

Nice!

I am curious: why does the completed handler for the storyboard de-register itself?

 

Bryant Likes

19 feb 2009

 

There actually is a built in template, but I think it is the one for WPF. I usually just type propdp tab tab and then change UIPropertyMetadata to just PropertyMetadata. But I like the new ones with all the change handlers, I’ll be adding those to my toolbox for sure.

Thanks!

 

Pete O'Hanlon

20 feb 2009

 

Robby – thanks for this. If you don’t mind, I might just wrap these up and add them into my MoXAML Power Toys addin for Visual Studio. I already have one for creating WPF DependencyProperties, it would be good to have the Silverlight versions as well – and you’ve saved me a fair bit of typing here.

I’ve also taken your Channel9 challenge, and I’m adding the Scrubber feature to MoXAML. I’ll be releasing it early next week. The current version is available at http://peteohanlon.wordpress.com/moxaml-power-toys/.

 

Robby Ingebretsen

20 feb 2009

 

@Rubens: If you just rename the .vsi to .zip and then unzip, you’ll see all of the .snippet files. I can’t believe that VS Express doesn’t know about .vsi. That’s too bad.

@Igor: Your right that deregistering the handler isn’t always necessary. I usually use this snippet “inline” though, like in a click handler for a button or something. So I’m registering that event every time someone clicks on the button. Because of that, I need to remove the handler or else the registered handlers will start to repeat…in other words, even though the storyboard only completes once, I’ll get a completed event notification for every time that I’ve registered a handler. If I were doing that in a button click handler, that would be once for every time the user clicks the button.

@Bryant: good point. It’s a small change to go from the built in DP snippet to one that works with Silverlight. So you should download these for the RSS datasource snippet! :)

@Pete: Feel free to include them with MoXAML. I’ll have to check that out. And getting XamlScrubber in VS will be awesome! I’ll be keeping an eye on it!

 

Pete O'Hanlon

22 feb 2009

 

Robby – I’ve just uploaded the new version of MoXAML with Scrubber inside. It scrubs all of the XAML in your project. It’s available at http://peteohanlon.wordpress.com/moxaml-power-toys/

 
 

[...] more. Along those lines, I was flattered that Page Brooks wanted to include my Silverlight snippets in the super handy Silverlight Contrib project. Nice! Way to go XAML community.  We’re [...]

 

Shawn Wildermuth

09 mar 2009

 

I ran into thse too late ;) I build a DP Snippet. Nice work and glad to see you’ll be in Silverlight Contrib!

http://wildermuth.com/2009/03/09/Silverlight_Dependency_Property_Snippet

 

Rubens

13 mar 2009

 

Robby thanks very much, it worked – and the snippets are excellent!

 
 

[...] automate the construction of this ghastly boiler-plate code. They are a few snippets available for Silverlight and whole host available WPF courtesy of the good Dr. These certainly help you get started, [...]

 
 

[...] them up in a single bundle for your convenience if you choose to use them.  I was going to package Robby’s snippets up as well, but didn’t think he’d appreciate that…you should get his Silverlight snippets as [...]

 
 

[...] up in a single bundle for your convenience if you choose to use them.  I was going to package Robby’s snippets up as well, but didn’t think he’d appreciate that…you should get hisSilverlight snippets as [...]

 
 

[...] If you try to run this it will fail. So how can we set this property in style? Well, a trick you can use is to set your own attached property and then have the property set the VerticalScrollBarVisibility property on the TextBox for you. Here is a very quick example that I cooked up (using Robby’s code snippet): [...]

 

Tbag

08 dec 2009

 

Any way you can convert these to support vb.net also?