在依赖项属性中获取“ this”指针更改了回调 [英] Getting 'this' pointer inside dependency property changed callback

查看:70
本文介绍了在依赖项属性中获取“ this”指针更改了回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类内具有以下依赖项属性:

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.

这是因为 FooHolder 具有一些事件处理程序,当属性值更改时,需要将该事件处理程序挂接/脱钩。更改后的属性回调必须是静态的,但事件处理程序不是。

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.

推荐答案

类似这样的事情:(您必须

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

当然,FooHolder必须继承DependencyObject

And, of course, FooHolder must inherit from DependencyObject

这篇关于在依赖项属性中获取“ this”指针更改了回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆