Getting 'this' pointer inside dependency property changed callback

后端 未结 3 983
温柔的废话
温柔的废话 2021-01-11 14:44

I have the following dependency property inside a class:

class FooHolder
{
    public static DependencyProperty CurrentFooProperty = DependencyProperty.Regis         


        
3条回答
  •  北海茫月
    2021-01-11 14:57

    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(string propertyName, Func> 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
            ("CurrentFoo", x => x.OnCurrentFooChanged);
    
        private void OnCurrentFooChanged(Foo oldFoo, Foo newFoo)
        {
            // do stuff with holder
        }
    }
    

提交回复
热议问题