gpt4 book ai didi

c# - Storyboard应用于许多元素

转载 作者:太空狗 更新时间:2023-10-29 23:31:05 25 4
gpt4 key购买 nike

我的 WPF 应用程序中有两个矩形。我想在单击某个元素时播放动画。动画应仅应用于单击的矩形。使用下面的代码,当我点击一个矩形时,所有的形状都会动画化。

我该怎么办??

Window.Resources>
<ResourceDictionary>

<LinearGradientBrush x:Key="ExecutionInitialization" EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="#FFC0FBBA"/>
<GradientStop Color="#FF0FA000" Offset="1"/>
<GradientStop Color="#FF0FA000"/>
</LinearGradientBrush>

<Storyboard x:Key="OnMouseLeftButtonDown1" RepeatBehavior="Forever">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(Shape.Fill).(GradientBrush.GradientStops)[0].(GradientStop.Offset)" Storyboard.TargetName="rec1">
<SplineDoubleKeyFrame KeyTime="0" Value="0.17"/>
<SplineDoubleKeyFrame KeyTime="0:0:0.4" Value="0.32"/>
<SplineDoubleKeyFrame KeyTime="0:0:0.8" Value="0.5"/>
<SplineDoubleKeyFrame KeyTime="0:0:1" Value="0.56"/>
<SplineDoubleKeyFrame KeyTime="0:0:1.2" Value="1"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</ResourceDictionary>


</Window.Resources>

<Grid>
<Rectangle MouseDown="rec1_MouseDown" Name="rec1" Fill="{StaticResource ExecutionInitialization}" HorizontalAlignment="Left" Height="85.075" Margin="24.358,27.731,0,0" Stroke="Red" VerticalAlignment="Top" Width="156.717"/>

<Rectangle MouseDown="rec2_MouseDown" Name="rec2" Fill="{StaticResource ExecutionInitialization}" HorizontalAlignment="Left" Height="113.433" Margin="246.746,141.164,0,0" Stroke="Black" VerticalAlignment="Center" Width="211.941"/>

</Grid>

和 c#

public MainWindow()
{
InitializeComponent();
animation = TryFindResource("OnMouseLeftButtonDown1") as Storyboard;
}

private void rec1_MouseDown(object sender, MouseButtonEventArgs e)
{
animation.Begin();
}

private void rec2_MouseDown(object sender, MouseButtonEventArgs e)
{

}

最佳答案

只需在 LinearGradientBrush 资源上将 x:Shared 属性设置为 false。然后,每个 Rectangle 的 Fill 属性都会获得自己分配的 Brush 副本。

<LinearGradientBrush x:Key="ExecutionInitialization" x:Shared="false"
EndPoint="0.5,1" StartPoint="0.5,0">
...
</LinearGradientBrush>

为了在不同的矩形上独立运行动画,您还必须删除 Storyboard.TargetName,并以目标控件作为参数启动 Storybord:

private void Rectangle_MouseDown(object sender, MouseButtonEventArgs e)
{
var storyboard = TryFindResource("OnMouseLeftButtonDown1") as Storyboard;
storyboard.Begin((FrameworkElement)sender);
}

然后您还可以对所有此类矩形使用相同的事件处理程序:

<Rectangle x:Name="rec1" MouseDown="Rectangle_MouseDown" .../>
<Rectangle x:Name="rec2" MouseDown="Rectangle_MouseDown" .../>

关于c# - Storyboard应用于许多元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24864631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com