Thursday, June 3, 2010

Dependency Properties Made Easy

ok so I found that for some reason I thought I did a post on this before and I couldn't find it. So I thought I would make a new post as simple as possible. Here is a simple dp:


public readonly DependencyProperty ResistanceProperty = DependencyProperty.Register("Resistance", typeof(double), typeof(AnimatingPanelBase), null);
public double Resistance
{
get
{
return (double)GetValue(ResistanceProperty);
}
set
{
SetValue(ResistanceProperty, value);
}
}

Nice and simple right? why bother you ask, well the biggest issue is that if you want to animate properties of a custom control of some kind using data binding and what that change to filter into the UI of some control. Otherwise I try to avoid DP's as much as possible. So if you need todo some mucking around in your control after the DP value has changed then do this:

public static readonly DependencyProperty MinimumProperty = DependencyProperty.Register("Minimum", typeof(double), typeof(Dial), new PropertyMetadata(new PropertyChangedCallback(OnMinimumChanged)));

public double Minimum
{
get
{
return (double)GetValue(MinimumProperty);
}
set
{
SetValue(MinimumProperty, value);
}
}
private static void OnMinimumChanged(DependencyObject DpObj, DependencyPropertyChangedEventArgs e)
{
// some code :
}

You'll note that this has a changed handler but otherwise is like the first version. and that is pretty much it. :)

2 comments:

  1. On thing I would add on this, which was an occasional issue with some of the development work I've done in the past.

    When setting default values on DPs, make sure you have explicitly defined the value, no inference of a value is made during runtime.

    For your example if you wanted a default value for say blending etc. you might tweak your DP register method's PropertyMetadata as such:

    public static readonly DependencyProperty MinimumProperty =
    DependencyProperty.Register("Minimum", typeof(double), typeof(Dial),
    new PropertyMetadata(0.0, new PropertyChangedCallback(OnMinimumChanged)));

    Notice how the default value on the PropertyMetadata isn't just 0. If the value isn't 0.0 (for this specific scenario) it will throw a run time error when that DP is called either in Blend or in the SL app.

    One other thing to add to this. Robby Ingebretsen has some great snippets for DPs that save a ton of time.
    http://blog.nerdplusart.com/archives/silverlight-code-snippets

    ReplyDelete
  2. Are you trying to earn money from your visitors by using popunder ads?
    If so, have you ever used Ero-Advertising?

    ReplyDelete