如何向现有的依赖关系属性回调添加逻辑? [英] How can I add logic to an existing dependency-property callback?

查看:176
本文介绍了如何向现有的依赖关系属性回调添加逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图添加一个PropertyChangedCallback到UIElement.RenderTransformOriginProperty。当我尝试覆盖PropertyMetadata时抛出异常。

I'm trying to add a PropertyChangedCallback to UIElement.RenderTransformOriginProperty. An exception is thrown when I try to override the PropertyMetadata.

我已经搜索到MSDN和Google,所有我能够想出的是这个。 DependencyPropertyDescriptor.AddValueChanged在该帖子的某个时候被建议,但这不会解决我的问题,因为这不是一个每个实例的回调。

I have searched MSDN and Google, and all I have been able to come up with is this. DependencyPropertyDescriptor.AddValueChanged is suggested at some point in that post, but that won't solve my problem since this is not a per-instance callback.

我不明白这个异常是什么意思。有谁知道我做错了什么?

I don't understand what this exception means at all. Does anyone know what I am doing wrong?

public class foo : FrameworkElement
{
    private static void Origin_Changed( DependencyObject d,
                                        DependencyPropertyChangedEventArgs e)
    { }

    static foo()
    {
        PropertyMetadata OriginalMetaData =
            UIElement.RenderTransformOriginProperty.GetMetadata(
                typeof(FrameworkElement));



/*An exception is thrown when this line is executed:
 "Cannot change property metadata after it has been associated with a property"*/
        OriginalMetaData.PropertyChangedCallback +=
            new PropertyChangedCallback(Origin_Changed);



        UIElement.RenderTransformOriginProperty.OverrideMetadata(
            typeof(foo), OriginalMetaData);
    }
}


推荐答案

WPF当您调用OverrideMetadata时,将合并您的属性元数据,不需要传递原始元数据对象。所以你需要做的只是

WPF will merge the property metadata for you when you call OverrideMetadata, no need to pass it the original Metadata object. So all you have to do is

UIElement.RenderTransformOriginProperty.OverrideMetadata(typeof(foo), new PropertyMetadata(new PropertyChangedCallback(Origin_Changed)));

有一件事要注意的是有时上面的代码抛出异常。发生这种情况的两种情况是

One thing to be aware of is sometimes the code above throws an exception. The two cases where that happens are

1。原始元数据是PropertyMetadata的子类 - 我已经看到了FrameworkPropertyMetadata和UIPropertyMetadata。您只需在每种情况下使用适当的。

1. The original metadata is a subclass of PropertyMetadata - I have seen FrameworkPropertyMetadata and UIPropertyMetadata. You just have to use the appropriate one in each case.

2。依赖属性是只读的,您不能做任何事情它。

2. The dependency property is read only and you can't do anything about it.

这篇关于如何向现有的依赖关系属性回调添加逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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