Silverlight Code Snippets for DependencyProperties and other Handy Stuff

I was teaching someone about DependencyProperty.aspx) 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 dependencything 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{: .button}

If you’re new to VS snippets, you can get the skinny here.aspx). 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.


Published

Discussion

Loading... Show

Previous