Cover

Silverlight Dependency Property Snippet

March 9, 2009
No Comments.

Url: http://wilderminds.blob.core.windows.net/downloads/sldp.zip

I’ve been teaching Silverlight for a couple of years now and when I get to the story of Dependency Properties, there is usually a collective groan when I refactor a simple property into a Dependency Property. Building them is easy but there is too much code.  If this were back in the C++ days, I would have just build a macro that was impossible to debug into…but those days are gone. Instead I wrote a simple snippet.

You might be wondering, “But there is already a Dependency Property snippet!”.  Yes there is: “propdp” in C# and “wpfdp” in Visual Basic.  But they are both for WPF not for Silverlight.  In addition, I didn’t like that a changed event handler wasn’t generated as its often needed. To that end I wrote a new snippet.

To install the snippet, download the sldp.zip file and open the sldp.snippet file. In Visual Studio, use the Tools->Code Snippets Manager:

I only wrote a C# version (anyone who wants to modify it for VB, feel free and drop me a copy and i’ll link it here).  So In the dialog that is opened, pick Visual C# and click the Import button:

Next navigate to and pick the sldp.snippet file that you expanded from the zip file.  This will leave you in the final part of the Import Code Snippet dialog:

Close the two dialogs and you can simply type **sldp **and tab twice to create your new snippet.  An example of the code generated is shown below:

public string TheName
{
  get { return (string)GetValue(TheNameProperty); }
  set { SetValue(TheNameProperty, value); }
}

// Using a DependencyProperty as the backing store for TheName.  
// This enables animation, styling, binding, etc...
public static readonly DependencyProperty TheNameProperty =
    DependencyProperty.Register("TheName",
                                typeof(string),
                                typeof(HelloView),
                                new PropertyMetadata("",
                                  new PropertyChangedCallback(
                                    OnTheNameChanged)));

static void OnTheNameChanged(object sender, 
                             DependencyPropertyChangedEventArgs args)
{
  // Get reference to self
  HelloView source = (HelloView)sender;

  // Add Handling Code
  string newValue = (string)args.newValue;
}

Enjoy and if you have questions or improvements, let me know.

UPDATE:

After building this, I found these handy Silverlight Snippets (including two snippets to replace my one DependencyProperty snippet):

http://blog.nerdplusart.com/archives/silverlight-code-snippets

They will also be included in Page Brooks’ Silverlight Contrib project:

http://silverlightcontrib.codeplex.com