我想我会添加另一个解决方案,使用 Expression SDK 中的行为并将其与 @Thomas 的解决方案相结合。使用它,我们可以定义一个“CloseBehavior”来处理启动故事板并在完成后关闭窗口的代码。
using System.ComponentModel;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Media.Animation;
namespace Presentation.Behaviours {
public class CloseBehavior : Behavior<Window> {
public static readonly DependencyProperty StoryboardProperty =
DependencyProperty.Register("Storyboard", typeof(Storyboard), typeof(CloseBehavior), new PropertyMetadata(default(Storyboard)));
public Storyboard Storyboard {
get { return (Storyboard)GetValue(StoryboardProperty); }
set { SetValue(StoryboardProperty, value); }
}
protected override void OnAttached() {
base.OnAttached();
AssociatedObject.Closing += onWindowClosing;
}
private void onWindowClosing(object sender, CancelEventArgs e) {
if (Storyboard == null) {
return;
}
e.Cancel = true;
AssociatedObject.Closing -= onWindowClosing;
Storyboard.Completed += (o, a) => AssociatedObject.Close();
Storyboard.Begin(AssociatedObject);
}
}
}
该行为将故事板定义为依赖属性,因此我们可以在 xaml 中设置它,并且当AssociatedObject
(我们定义行为的窗口)关闭时,该故事板使用Storyboard.Begin()
. 现在,在 xaml 中,我们只需使用以下 xaml 将行为添加到窗口
<Window x:Class="Presentation.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:behave="clr-namespace:Presentation.Behaviours"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
x:Name="window">
<Window.Resources>
<Storyboard x:Key="ExitAnimation">
<DoubleAnimation Storyboard.Target="{Binding ElementName='window'}"
Storyboard.TargetProperty="(Window.Opacity)"
Duration="0:0:1" From="1" To="0"/>
</Storyboard>
</Window.Resources>
<i:Interaction.Behaviors>
<behave:CloseBehavior Storyboard="{StaticResource ExitAnimation}"/>
</i:Interaction.Behaviors>
<Grid>
</Grid>
</Window>
请注意 System.Windows.Interactivity dll 中的 xml 命名空间i
,并且还引用了该窗口,因此必须对其进行x:Name
分配。现在我们只需在关闭应用程序之前将行为添加到我们希望在其上执行情节提要的每个窗口,而不是将逻辑复制到每个窗口中的每个代码隐藏。