PointAnimation定位自定义UserControl属性

时间:2015-05-14 23:46:31

标签: c# wpf animation storyboard

我试图动画我创建的UserControl的位置。 我的问题与MSDN上提出的这个问题非常相似,但没有得到答案。

https://social.msdn.microsoft.com/Forums/vstudio/en-US/11ce8aaa-1059-4fe5-8f4d-0fa7978e6ff2/using-pointanimation-to-move-a-control?forum=wpf

总结一下,我创建了一个名为' Position'的Point类型依赖属性。我用来在UI上指定UserControl的位置,并希望将UserConrol设置为新位置的动画。

我的问题是我认为的语法,我不确定定位我的UserControl属性的正确语法(在代码隐藏中)。

public class SubContainer : Control 
{ 
 public static readonly DependencyProperty PositionProperty; 

 static SubContainer() 
 { 
    DefaultStyleKeyProperty.OverrideMetadata(typeof(SubContainer), 
        new FrameworkPropertyMetadata(typeof(SubContainer))); 

    PositionProperty = DependencyProperty.Register( 
        "Position", 
        typeof(Point), 
        typeof(SubContainer), 
        new PropertyMetadata(new Point(0, 0))); 
 } 

 public Point Position 
 { 
    get { return (Point)GetValue(PositionProperty); } 
    set { SetValue(PositionProperty, value); } 
 } 

然后是我的动画:

        public void BoxTransition()
    {
        Point destination = new Point(70, 300);
        SubContainer box = (MainContent.Children[0] as Container).Children[0] as SubContainer;
        PointAnimation transition = new PointAnimation();
        TimeSpan timespan = TimeSpan.FromSeconds(2);

        this.RegisterName("Target", box.Position);
        Transition.From = box.Position;
        Transition.To = destination;
        Storyboard.SetTargetName(transition, "Target");
        Storyboard.SetTargetProperty(transition, new PropertyPath(box.Position));
        Storyboard bTransition = new Storyboard();
        bTransition.Children.Add(transition);
        bTransition.Begin();

    }

我收到以下错误:

对象' System.Windows.Point'不能用作PropertyPath的访问器参数。访问者参数必须是DependencyProperty,PropertyInfo或PropertyDescriptor。

任何使我的控制动画的替代方案也将非常感激!

2 个答案:

答案 0 :(得分:0)

好的,问题解决了。使用Expression Blend满足您的所有动画需求。结束;)

答案 1 :(得分:0)

WPF允许在没有故事板的情况下直接启动UIElement属性的动画。

您不需要更多代码:

var transition = new PointAnimation
{
    To = new Point(70, 300),
    Duration = TimeSpan.FromSeconds(2)
};

box.BeginAnimation(SubContainer.PositionProperty, transition);

请注意,上述内容未设置PointAnimation的From属性。这样,动画将从Position属性的当前值开始。

作为Position属性的替代,您可以将SubContainer控件放在Canvas中

<Canvas>
    <local:SubContainer x:Name="box" Canvas.Left="0" Canvas.Top="0" .../>
</Canvas>

并为其Canvas.LeftCanvas.Top属性制作动画:

var duration = TimeSpan.FromSeconds(2);
box.BeginAnimation(Canvas.LeftProperty,
    new DoubleAnimation { To = 70, Duration = duration });
box.BeginAnimation(Canvas.TopProperty,
    new DoubleAnimation { To = 300, Duration = duration });