Getting 'this' pointer inside dependency property changed callback

浪子不回头ぞ 提交于 2019-12-01 03:07:28

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

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

Based on @catalin-dicu 's answer, I added this helper method to my library. It felt a bit more natural to have the OnChanged method be non-static and to hide all the casting.

static class WpfUtils
{
    public static DependencyProperty RegisterDependencyPropertyWithCallback<TObject, TProperty>(string propertyName, Func<TObject, Action<TProperty, TProperty>> getOnChanged)
        where TObject : DependencyObject
    {
        return DependencyProperty.Register(
            propertyName,
            typeof(TProperty),
            typeof(TObject),
            new PropertyMetadata(new PropertyChangedCallback((d, e) =>
                getOnChanged((TObject)d)((TProperty)e.OldValue, (TProperty)e.NewValue)
            ))
        );
    }
}

Usage example:

class FooHolder
{
    public static DependencyProperty CurrentFooProperty = WpfUtils.RegisterDependencyPropertyWithCallback
        <FooHolder, Foo>("CurrentFoo", x => x.OnCurrentFooChanged);

    private void OnCurrentFooChanged(Foo oldFoo, Foo newFoo)
    {
        // do stuff with holder
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!