Monday 11 April 2011

Creating Styles with Storyboard Animation in Powershell

Here is an example of an event trigger which animates the color of a textbox on the MouseEnter event firing.

$trigger1=New-Object Windows.Eventtrigger([Windows.Controls.Textbox]::MouseEnterEvent);
$trigger1.Actions.Add((New-Object windows.Media.Animation.BeginStoryBoard));
$bsbitem=$trigger1.Actions.Item(0);
$bsbitem.StoryBoard=New-Object windows.Media.Animation.StoryBoard;
$bsbitem.StoryBoard.Children.Add((New-Object windows.media.animation.coloranimation([Windows.Media.Colors]::LightBlue,[Timespan]::FromSeconds(1))));
[Windows.Media.Animation.StoryBoard]::SetTargetProperty($bsbitem.StoryBoard.Children.Item(0),[Windows.PropertyPath] "Background.Color");
$styletxtbox.Triggers.Add($trigger1);

Several things should be noted:
  1. You create the EventTrigger using the associated event from the type you are animating.
  2. $styletxtbox is a Windows.Style object.
  3. The trigger events mouse be events derived from Windows.TriggerAction.  This means they must be either wrappers for a Storyboard, or a SoundPlayerAction.  You can use Keyframes to quickly change a color, or use the smooth transitions defined in the inheritance hierarchy for Windows.Media.Animation.Animationtimeline
  4. Set the property operated on  via [Windows.Media.Animation.StoryBoard]::SetTargetProperty.
The question might be raised, why not just use XAML and save yourself all the trouble?  Well, there are several answers to that, most of which focus around.
  • The wastefulness of dynamically generating XAML code for a dynamic form, parsing it and creating the objects VS just creating or manipulating the objects involved directly.
  • The capacity to easily reference every one of the elements of the form as a variable, for instance in writing event handlers.
The key here is to understand when it is necessary to use either declarative or procedural methodologies in evolving the objects.  Dynamic flexible data calls either for procedural design, or data templating, whichever fits more with your design methodology.  WPF supports both.

No comments:

Post a Comment