创建附加属性

Creating an attached property

我想研究如何创建一个简单的附加属性。例如,要在 canvas 上旋转图形。类似这样,但使用附加属性:

    <Canvas Margin="0 200">
        <Ellipse Fill="Red" Width="100" Height="60"
                 RenderTransformOrigin=".5, .5">
            <Ellipse.RenderTransform>
                <RotateTransform Angle="30"/>
            </Ellipse.RenderTransform>
        </Ellipse>
    </Canvas>

我创建了类:

class RotationManager : DependencyObject
{
    public static double GetAngle(DependencyObject obj)
    {
        return (double) obj.GetValue(AngleProperty);
    }

    public static void SetAngle(DependencyObject obj, double value)
    {
        obj.SetValue(AngleProperty, value);
    }

    private static void OnAngleChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        var element = obj as UIElement;
        if (element != null)
        {
            element.RenderTransformOrigin= new Point(.5, .5);
            var transform = new RotateTransform();
            transform.Angle = (double) e.NewValue;
            element.RenderTransform = transform;

        }                
    }

    public static readonly DependencyProperty AngleProperty =
        DependencyProperty.RegisterAttached("Angle",
            typeof (double), typeof (RotationManager),
            new PropertyMetadata(0.0, OnAngleChanged));
}

并修改了我的 XAML:

  <Canvas Margin="0 200">
        <Ellipse Fill="Red" Width="100" Height="60" 
                 local:RotationManager.Angle="45"/>
 </Canvas>

但是如果我添加 local:RotationManager.Angle="45",椭圆就会从 canvas 中消失。为什么 ? 我将断点设置到我的 RotationManager,但没有一个方法执行。

我该如何解决?

显然,在 Windows 运行时 class 需要 public:

public class RotationManager
{
    ...
}