我想要一个PropertyChangedCallback添加到UIElement.RenderTransformOriginProperty。当我尝试重写PropertyMetadata,则抛出异常。
我寻觅MSDN和谷歌,而我已经能够拿出的this. DependencyPropertyDescriptor.AddValueChanged建议在该职位的某个时刻,但不会解决我的问题,因为这不是每个实例的回调。
我不明白这是什么异常意味着在所有。有谁知道我在做什么错了?
公共类Foo:FrameworkElement的
{
私有静态无效Origin_Changed(DependencyObject的研发,
DependencyPropertyChangedEventArgs五)
{}
静态FOO()
{
PropertyMetadata OriginalMetaData =
UIElement.RenderTransformOriginProperty.GetMetadata(
typeof运算(FrameworkElement的));
/ *当执行这一行,则抛出异常:
无法更改属性的元数据后,它已经与物业相关的* /
OriginalMetaData.PropertyChangedCallback + =
新PropertyChangedCallback(Origin_Changed);
UIElement.RenderTransformOriginProperty.OverrideMetadata(
typeof运算(富),OriginalMetaData);
}
}
解决方案
WPF将合并属性的元数据为你,当你调用OverrideMetadata,没有必要通过它原来的元数据对象。因此,所有你需要做的就是
UIElement.RenderTransformOriginProperty.OverrideMetadata(typeof运算(富),新PropertyMetadata(新PropertyChangedCallback(Origin_Changed)));
有一点需要注意的是有时候code以上抛出一个异常。这两种情况下,出现这种情况是
1 原来的元数据是PropertyMetadata的一个子类 - 我见过FrameworkPropertyMetadata和UIPropertyMetadata。你只需要使用适当的一个在每种情况下。
2 的依赖项属性是只读的,你不能做任何事情。
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);
}
}
解决方案
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.