I want to fade a window in/out in my application.
Fading in occurs on Window.Loaded
and I wanted to fade out on close (Window.Closed
or Window.Closing
).
Fading in works perfectly, but Window.Closing
is not allowed value for RoutedEvent
property.
What RoutedEvent
should I be using for Close?
<Window.Triggers>
<EventTrigger RoutedEvent="Window.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:2" FillBehavior="HoldEnd" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="Window.Closing">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:2" FillBehavior="HoldEnd" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Window.Triggers>
I get a error on , Value 'Window.Closing' cannot be assigned to property 'RoutedEvent'. Invalid event name.
Closing is not a routed event, so you can't use it in an EventTrigger. Perhaps you could start the storyboard in the handler of the ClosingEvent in the code-behind and cancel the event... something like that :
This is even simpler and shorter. Add a behavior as follows:
Then in your window add a reference :
Insert the behavior:
I thought I'd add another solution of doing this, using behaviors from the Expression SDK and combining it with the solution from @Thomas. Using that, we can define a "CloseBehavior" that handles the code behind of starting a storyboard and closing the window when it's done.
The behavior defines a storyboard as a dependency property, so we can set it in xaml and when the
AssociatedObject
(the window where we define the behavior) is closing, this storyboard is started usingStoryboard.Begin()
. Now, in xaml we simply add the behavior to the window using the following xamlNote the xml namespace
i
from the System.Windows.Interactivity dll, and also that the window is referenced, so it has to have ax:Name
assigned. Now we simply add the behavior to every window on which we wish to execute a storyboard before closing the application, instead of copying the logic to every code-behind in each window.Set AutoReverse To "True"
I'm not an expert on WPF but I believe that unless you cancel the initial Closing event the window will be gone before the animation is even started.
Upon receiving the Window.Closing event, you should cancel the event and start the animation. When the animation is done you can close the window.