通过代码对多个元素的变换比例进行动画处理:c#



我有一堆像这样的网格元素:

<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 循环中,因此我可以遍历所有网格。当我尝试运行它时,它会在"故事板"中抛出错误。开始(这个,真的(;">

"System.InvalidOperationException",描述说对象不支持此属性"RenderTransform.Children[0]。ScaleX"。但它应该支持这一点,因为它基本上与我之前在手动编写的故事板中使用的方法100%相同。有谁知道这里发生了什么?

我通过将"x:Name"放入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);

最新更新