在WPF中多个文本同时闪烁
时间: 2024-03-06 16:51:49 浏览: 21
要在 WPF 中实现多个文本同时闪烁,可以使用多个 Storyboard 和 DoubleAnimation 来控制它们的闪烁效果。以下是一个示例代码,你可以根据自己的需求进行调整。
```xaml
<Window.Resources>
<Storyboard x:Key="Text1Storyboard" RepeatBehavior="Forever">
<DoubleAnimation Storyboard.TargetName="Text1"
Storyboard.TargetProperty="Opacity"
From="1" To="0" Duration="0:0:0.5" />
</Storyboard>
<Storyboard x:Key="Text2Storyboard" RepeatBehavior="Forever">
<DoubleAnimation Storyboard.TargetName="Text2"
Storyboard.TargetProperty="Opacity"
From="1" To="0" Duration="0:0:0.5" />
</Storyboard>
</Window.Resources>
<Grid>
<TextBlock x:Name="Text1" Text="Text 1" FontSize="24" Foreground="Red" />
<TextBlock x:Name="Text2" Text="Text 2" FontSize="24" Foreground="Blue" Margin="0,30,0,0" />
</Grid>
```
在代码中,我们定义了两个名为 Text1Storyboard 和 Text2Storyboard 的 Storyboard,它们都是无限循环的动画,通过控制 Text1 和 Text2 的 Opacity 属性来实现文本的闪烁效果。
在窗口中,我们添加了两个 TextBlock 控件,分别显示了文本 "Text 1" 和 "Text 2"。通过设置它们的 FontSize、Foreground 和 Margin 属性,我们可以控制文本的样式和位置。
最后,我们将 Text1Storyboard 和 Text2Storyboard 与窗口的 Loaded 事件关联,这样当窗口加载完成后,动画就会开始运行。
```csharp
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var text1Storyboard = FindResource("Text1Storyboard") as Storyboard;
text1Storyboard.Begin();
var text2Storyboard = FindResource("Text2Storyboard") as Storyboard;
text2Storyboard.Begin();
}
```
在代码中,我们获取名为 Text1Storyboard 和 Text2Storyboard 的 Storyboard 对象,并调用 Begin() 方法来开始动画。