Freedom isn’t free [Tip: When creating a DependencyProperty, follow the handy convention of "wrapper+register+static+virtual"]


This blog has moved to a new location and comments have been disabled.

All old posts, new posts, and comments can be found on The blog of dlaa.me.

See you there!

Comments (5)

  1. jimmccurdy says:

    using a lambda expression, you can reduce this pattern to "wrapper+register+virtual" as follows:

    <pre>

    public int MyProperty

    {

    get { return (int)GetValue(MyPropertyProperty); }

    set { SetValue(MyPropertyProperty, value); }

    }

    public static readonly DependencyProperty MyPropertyProperty =

    DependencyProperty.Register("MyProperty", typeof(int), typeof(MyControl),

    new PropertyMetadata(0, (d, e) => ((MyControl)d).OnMyPropertyChanged((int)e.OldValue, (int)e.NewValue)));

    protected virtual void OnMyPropertyChanged(int oldValue, int newValue)

    {

    // TODO: Handle property change

    }

    </pre>

  2. Delay says:

    jimmccurdy,

    Good point, thanks!

    Without analyzing it too much, I don’t think that I’ll switch to this form because it’s been my experience that not everyone is comfortable with lambdas. And sometimes the auto-generated names they have are just painful to look at in the debugger. :|

    However, it hadn’t occurred to me to use a lambda in this scenario, so I really appreciate the suggestion!

  3. AnthonyWJones says:

    Probably the best way to create dependency properties is to use snippets.  Jeff Wilcox blogs about a useful set here:-

    http://www.jeff.wilcox.name/2010/02/silverlight-snippets/

    Tweak’em to preference if necessary

  4. Delay says:

    AnthonyWJones,

    Yes, those snippets came out of the team I’m on. :) Ted Glaza wrote them a year or two ago and they’ve been used internally since then.

  5. akjoshi says:

    I think VS itself have snippets for creating DP. I use "propdp" regularly.