简体   繁体   English

在依赖属性中获取'this'指针会改变回调

[英]Getting 'this' pointer inside dependency property changed callback

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. 这是因为FooHolder有一些事件处理程序需要在属性值更改时挂钩/取消挂钩。 The property changed callback must be static, but the event handler is not. 属性更改回调必须是静态的,但事件处理程序不是。

Something like this : (you'll have to define UnwireFoo() and WireFoo() yourself) 这样的事情:(你必须自己定义UnwireFoo()和WireFoo())

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 当然,FooHolder必须继承自DependencyObject

要更改的属性的所有者是回调方法的d参数

Based on @catalin-dicu 's answer, I added this helper method to my library. 根据@ catalin-dicu的回答,我将这个辅助方法添加到我的库中。 It felt a bit more natural to have the OnChanged method be non-static and to hide all the casting. 让OnChanged方法非静态并隐藏所有的转换感觉更自然一点。

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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM