storyboard创建动画问题
要求:
创建一个button(起始坐标为(0,0)),沿x轴方向由0移动到100
在xaml中可以正常实现(使用),实现方法如下:
- C# code
<Window.Resources> <Storyboard x:Key="sboard"> <DoubleAnimation Storyboard.TargetName="ttXaml" Storyboard.TargetProperty="X" Duration="00:00:01" From="0" To="30" /> </Storyboard> </Window.Resources> <Grid> <Button x:Name="button1" Content="click" Click="button1_Click" Width="50" Height="50"> <Rectangle.RenderTransform> <TranslateTransform x:Name="ttXaml"/> </Rectangle.RenderTransform> </Button> </Grid>
C#部分代码如下:
- C# code
(this.Resources["sboard"] as Storyboard).Begin();
代码运行正常,现在我想根据xaml代码转换成C#代码,我做了如下转换:
- C# code
TranslateTransform tt = new TranslateTransform(); // RotateTransform rt = new RotateTransform(); this.button1.RenderTransform = tt; this.button1.Name = "button1"; NameScope.SetNameScope(this, new NameScope()); this.RegisterName(this.button1.Name, this.button1); DoubleAnimation xAnimation = new DoubleAnimation(); xAnimation.From = 0; xAnimation.To = 100; xAnimation.Duration = new Duration(TimeSpan.FromSeconds(1)); DependencyProperty[] propertyChain = new DependencyProperty[] // 使用属性链的时候应用 { Button.RenderTransformProperty, TranslateTransform.XProperty, RotateTransform.AngleProperty // 调整角度时候用 }; Storyboard story = new Storyboard(); // story.AutoReverse = true; // story.RepeatBehavior = RepeatBehavior.Forever; story.Children.Add(xAnimation); //Storyboard.SetTargetName(xAnimation, this.button1.Name); //Storyboard.SetTargetProperty(xAnimation, new PropertyPath("(0).(1)", propertyChain)); Storyboard.SetTarget(xAnimation, tt); Storyboard.SetTargetProperty(xAnimation, new PropertyPath(TranslateTransform.XProperty)); //Storyboard.SetTarget(xAnimation, rt); //Storyboard.SetTargetProperty(xAnimation, new PropertyPath(RotateTransform.AngleProperty)); story.Begin(this);
运行之后却没有反应,但是,如果使用:
//Storyboard.SetTargetName(xAnimation, this.button1.Name);
//Storyboard.SetTargetProperty(xAnimation, new PropertyPath("(0).(1)", propertyChain));
这个方法就可以得到想要的效果。
我看xaml代码部分的TargeName属性设置为了"ttXaml"也就是对应对象是TranslateTransform变形啊,为什么我在C#代买中这样写就没有效果呢?能帮忙看下是否代码写错了?
非常感谢!
[解决办法]
“RenderTrasform.X"
A Storyboard can be used to animate dependency properties of animatable classes (for more information about what makes a class animatable, see the Animation Overview). However, because storyboarding is a framework-level feature, the object must belong to the NameScope of a FrameworkElement or a FrameworkContentElement.
http://nonocast.cn/?p=2454