我有一个带有标签控件的WPF窗口,用于向用户发送消息.几秒钟后,我希望消息消失.我创建了一个DispatcherTimer和一个故事板来做到这一点.(计时器延迟5秒,然后点击事件触发,消息消失.)它成功消失,但下一条消息仍然将其不透明度设置为0.(因此用户无法看到它.)显然,我试过了将不透明度设置回1,但失败并没有例外.(也就是说,我可以毫无问题地跨过那行代码,但是在执行它之后不透明度仍为0.)谁能告诉我我做错了什么?以下是来自测试项目的一些代码,只有标签控件,设置标签内容和淡入淡出动画的按钮,以及尝试重置不透明度的按钮.
XAML:
<Window x:Class="WpfTestApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="100" Width="525">
<Grid>
<StackPanel x:Name="stkHeaderBar" Grid.Row="0" Background="{DynamicResource {x:Static SystemColors.ControlDarkBrushKey}}" Orientation="Horizontal" FlowDirection="RightToLeft">
<Label x:Name="lblTest" Content="lblTest"/>
<Button x:Name="btnChangeLabel" Content="ChangeLabel" Click="btnChangeLabel_Click"/>
<Button x:Name="btnResetOpacity" Content="Reset Opacity" Click="btnResetOpacity_Click"/>
</StackPanel>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)
C#:
private void btnChangeLabel_Click(object sender, RoutedEventArgs e)
{
lblTest.Content = "Testing1...Testing2...Testing3";
lblTest.Opacity = 1;
// Create a storyboard to contain the animations.
Storyboard storyboard = new Storyboard();
TimeSpan duration = new TimeSpan(0, 0, 2);
// Create a DoubleAnimation to fade the not selected option control
DoubleAnimation animation = new DoubleAnimation();
animation.From = 1.0;
animation.To = 0.0;
animation.Duration = new Duration(duration);
// Configure the animation to target de property Opacity
Storyboard.SetTargetName(animation, lblTest.Name);
Storyboard.SetTargetProperty(animation, new PropertyPath(Control.OpacityProperty));
// Add the animation to the storyboard
storyboard.Children.Add(animation);
// Begin the storyboard
storyboard.Begin(this);
}
private void btnResetOpacity_Click(object sender, RoutedEventArgs e)
{
lblTest.Opacity = 1;
}
Run Code Online (Sandbox Code Playgroud)
Cle*_*ens 11
默认情况下,动画FillBehavior设置为HoldEnd,这意味着动画保存目标属性的最终值.如果要稍后重置该值,则需要删除动画,或者将FillBehavior设置为Stop.然后,您可以为动画的Completed事件添加处理程序以手动保留最终值.
另请注意,您不需要计时器来延迟动画的开始.您可以BeginTime改为设置其属性.
最后,不需要Storyboard来为单个属性设置动画.你可以打个电话UIElement.BeginAnimation.
private void btnChangeLabel_Click(object sender, RoutedEventArgs e)
{
var animation = new DoubleAnimation
{
To = 0,
BeginTime = TimeSpan.FromSeconds(5),
Duration = TimeSpan.FromSeconds(2),
FillBehavior = FillBehavior.Stop
};
animation.Completed += (s, a) => lblTest.Opacity = 0;
lblTest.BeginAnimation(UIElement.OpacityProperty, animation);
}
private void btnResetOpacity_Click(object sender, RoutedEventArgs e)
{
lblTest.Opacity = 1;
}
Run Code Online (Sandbox Code Playgroud)