我有一堆像这样的网格元素:
<Grid x:Name="LevelSegment6" Opacity="1" Canvas.Left="224" Canvas.Top="109" Width="19" Height="33" Background="{DynamicResource SpiritLevelSegment}" RenderTransformOrigin="0.5,0.5">
<Grid.RenderTransform>
<TransformGroup>
<ScaleTransform CenterX="-1" CenterY="0" ScaleX="0" ScaleY="0"/>
<RotateTransform Angle="90"/>
</TransformGroup>
</Grid.RenderTransform>
</Grid>
这是24个网格元素之一。所有这些都有不同的画布位置和角度。但是,必须对ScaleX和ScaleY值进行动画处理。
测试我编写和测试故事板的所有内容,如下所示:
<Storyboard x:Key="storyboard">
<DoubleAnimation Storyboard.TargetName="LevelSegment6" Storyboard.TargetProperty="RenderTransform.Children[0].ScaleX" To="0.3" BeginTime="0:0:0" Duration="0:0:0.5"/>
<DoubleAnimation Storyboard.TargetName="LevelSegment6" Storyboard.TargetProperty="RenderTransform.Children[0].ScaleY" To="0.6" BeginTime="0:0:0" Duration="0:0:0.5"/>
</Storyboard>
当我启动故事板时,元素按预期动画,但只有故事板中定义的一个元素。为每个代码创建此故事板的所有内容设置动画,并同时为所有24个网格运行24个这样的故事板。
这是生成和运行这些故事板的代码:
DoubleAnimation animx = new DoubleAnimation();
animx.Duration = TimeSpan.FromSeconds(0.5);
animx.BeginTime = TimeSpan.FromMilliseconds(0);
animx.To = 0.5;
DoubleAnimation animy = new DoubleAnimation();
animy.Duration = TimeSpan.FromSeconds(0.5);
animy.BeginTime = TimeSpan.FromMilliseconds(0);
animy.To = 0.5;
Storyboard.SetTargetName(animx, "LevelSegment" + i.ToString());
Storyboard.SetTargetProperty(animx, new PropertyPath("RenderTransform.Children[0].ScaleX"));
Storyboard.SetTargetName(animy, "LevelSegment" + i.ToString());
Storyboard.SetTargetProperty(animy, new PropertyPath("RenderTransform.Children[0].ScaleY"));
Storyboard storyboard = new Storyboard();
storyboard.Children.Add(animx);
storyboard.Children.Add(animy);
storyboard.Begin(this, true);
所有这些显然都在for循环中,所以我可以浏览所有的网格。当我尝试运行它时,它会在&#34; storyboard.Begin(this,true)中引发错误;&#34;
&#34; System.InvalidOperationException&#34;并且描述说该对象不支持此属性&#34; RenderTransform.Children [0] .ScaleX&#34;。但它应该支持这个,因为它基本上是我在手动编写的故事板中使用的方法100%。有谁知道这里发生了什么?
答案 0 :(得分:0)
我通过放置&#34; x:Name&#34;来修复它。进入ScaleTransform而不是网格:
<Grid Opacity="1" Canvas.Left="224" Canvas.Top="109" Width="19" Height="33" Background="{DynamicResource SpiritLevelSegment}" RenderTransformOrigin="0.5,0.5">
<Grid.RenderTransform>
<TransformGroup>
<ScaleTransform x:Name="LevelSegment6" CenterX="-1" CenterY="0" ScaleX="0" ScaleY="0"/>
<RotateTransform Angle="90"/>
</TransformGroup>
</Grid.RenderTransform>
</Grid>
通过这样做,我还可以直接为该属性设置动画,而无需使用故事板:
DoubleAnimation animx = new DoubleAnimation();
animx.Duration = TimeSpan.FromSeconds(0.5);
animx.BeginTime = TimeSpan.FromMilliseconds(0);
animx.To = 0.3;
DoubleAnimation animy = new DoubleAnimation();
animy.Duration = TimeSpan.FromSeconds(0.5);
animy.BeginTime = TimeSpan.FromMilliseconds(0);
animy.To = 0.6;
ScaleTransform scale = (ScaleTransform)FindName("LevelSegment" + i.ToString());
scale.BeginAnimation(ScaleTransform.ScaleXProperty, animx);
scale.BeginAnimation(ScaleTransform.ScaleYProperty, animy);