Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

c# - How can I add logic to an existing dependency-property callback?

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

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. 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. The dependency property is read only and you can't do anything about it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...