我有一个自定义按钮。出于某种原因,我想在代码中应用转换。变换工作正常。但是当我尝试在变换上添加动画时,动画不会生效。我的代码如下。
public partial class MyButton : Button
{
private TranslateTransform translate = new TranslateTransform() { X = 200, Y = 100 };
public MyButton()
{
InitializeComponent();
this.RenderTransform = new TransformGroup()
{
Children =
{
this.translate
}
};
}
protected override void OnClick()
{
base.OnClick();
// Edit: I need to use Storyboard to synchronized animation1 and animation2.
var sb = new Storyboard();
var animation1 = new DoubleAnimation(200, -10, new Duration(new TimeSpan(0, 0, 0, 1, 0)));
Storyboard.SetTarget(animation1, this.translate);
Storyboard.SetTargetProperty(animation1, new PropertyPath("X"));
sb.Children.Add(animation1);
var animation2 = new DoubleAnimation(100, 0, new Duration(new TimeSpan(0, 0, 0, 1, 0)));
Storyboard.SetTarget(animation2, this.translate);
Storyboard.SetTargetProperty(animation2, new PropertyPath("Y"));
sb.Children.Add(animation2);
sb.Begin(this);
}
}
有人可以解释为什么以及如何为这种情况添加动画?
答案 0 :(得分:1)
SetTarget()
不起作用。我不知道为什么不,我没有调查。我刚刚测试了the workaround,发现它很好。
请注意,您必须在构造函数中执行NameScope
/ RegisterName
内容。
public MyButton()
{
InitializeComponent();
this.RenderTransform = new TransformGroup()
{
Children =
{
this.translate
}
};
NameScope.SetNameScope(this, new NameScope());
RegisterName("translate", this.translate);
}
protected override void OnClick()
{
base.OnClick();
var sb = new Storyboard();
var animation1 = new DoubleAnimation(200, -10, new Duration(new TimeSpan(0, 0, 0, 1, 0)));
Storyboard.SetTargetName(animation1, "translate");
Storyboard.SetTargetProperty(animation1, new PropertyPath(TranslateTransform.XProperty));
sb.Children.Add(animation1);
var animation2 = new DoubleAnimation(100, 0, new Duration(new TimeSpan(0, 0, 0, 1, 0)));
Storyboard.SetTargetName(animation2, "translate");
Storyboard.SetTargetProperty(animation2, new PropertyPath(TranslateTransform.YProperty));
sb.Children.Add(animation2);
sb.Begin(this);
}
您无需使用相同的参数创建两个不同的动画。原来你也不需要故事板;这是为一个事件或某事开始动画。我不知道你为什么不google这个。谷歌自动完成了“wpf storyboard animation ......”。 It's here, anyway。
protected override void OnClick()
{
base.OnClick();
var animation1 = new DoubleAnimation(100, 0,
new Duration(new TimeSpan(0, 0, 0, 1, 0)));
translate.BeginAnimation(TranslateTransform.XProperty, animation1);
translate.BeginAnimation(TranslateTransform.YProperty, animation1);
}