DependencyPropertyChangedEventArgs? Think Again.

Delegate Contravariance is a really cool feature in C# that is often overlooked, mostly because it is so implicit and “obvious”. Go read the example I linked to if you don’t know what it is (it’s a short one).

The following code, however, will not compile, even though you’d expect it to:

public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(MyControl),
new FrameworkPropertyMetadata(0, new PropertyChangedCallback(OnMyPropertyChanged)));
public int MyProperty
{
get { return (int)this.GetValue(MyPropertyProperty); }
set { this.SetValue(MyPropertyProperty, value); }
}
private static void OnMyPropertyChanged(object sender, EventArgs e)
{
((MyControl)sender).OnMyPropertyChanged(e);
}
protected virtual void OnMyPropertyChanged(EventArgs e)
{
if (this.MyPropertyChanged != null)
this.MyPropertyChanged(this, e);
}
public event EventHandler MyPropertyChanged;

This is due to the fact that the PropertyChangedCallback delegate, to which all property-changed methods must adhere, has two parameters: DependencyObject and DependencyPropertyChangedEventArgs. The problem lies in the DependencyPropertyChangedEventArgs value, since it does not inherit from EventArgs. It’s even a struct!
Bummer. Now we have to start writing plumbing code.

Incidentally, this is my 200th post… and it only took me a bit over four years :)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s