views:

215

answers:

2

I have the following dependency property inside a class:

class FooHolder
{
    public static DependencyProperty CurrentFooProperty = DependencyProperty.Register(
        "CurrentFoo",
        typeof(Foo), 
        typeof(FooHandler),
        new PropertyMetadata(OnCurrentFooChanged));

    private static void OnCurrentFooChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        FooHolder holder = (FooHolder) d.Property.Owner; // <- something like this

        // do stuff with holder
    }
}

I need to be able to retrieve a reference to the class instance in which the changed property belongs.

This is since FooHolder has some event handlers that needs to be hooked/unhooked when the value of the property is changed. The property changed callback must be static, but the event handler is not.

+4  A: 

Something like this : (you'll have to define UnwireFoo() and WireFoo() yourself)

private static void OnCurrentFooChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    FooHolder holder = (FooHolder)d; // <- something like this

    holder.UnwireFoo(e.OldValue as Foo);
    holder.WireFoo(e.NewValue as Foo);
}

And, of course, FooHolder must inherit from DependencyObject

Catalin DICU
And here I was looking around the properties *inside* d, maybe it was to obvious. Thanks!
mizipzor
+1  A: 

The owner of the property being changed is the d parameter of your callback method

Thomas Levesque