by gleblanc
2. November 2008 20:22
In this post, we will add (dynamically and by program) an animation to our previous drop-down and XML-driven menu. Just of few lines to add !
Project / source code
The artwork initially presented is "La montagne Sainte-Victoire" from Paul Cézanne.
As seen in the previous post, our sub-menus and menu items are dynamically created when needed. When a sub-menu is created, we just need to dynamically add a
Storyboard object. The code here is added in our
CreateSubMenu fonction, that accepts
mnu, of type
Menu, as argument. In our
Menu class, we added a field, named
stbShow and of type
Storyboard :
if (mnu.parentMenu != null) // not applicable to the main (horizontal) menu
{
// dynamically create storyboard
Storyboard stb = new Storyboard();
Storyboard.SetTarget(stb, mnu.menuContainer);
DoubleAnimation daHeight = new DoubleAnimation();
daHeight.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 400));
daHeight.From = 0; daHeight.To = mnu.lstMenuItems.Count * cellItemHeight;
Storyboard.SetTargetProperty(daHeight, new PropertyPath("Height"));
DoubleAnimation daWidth = new DoubleAnimation();
daWidth.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 400));
daWidth.From = 0; daWidth.To = mnu.Width;
Storyboard.SetTargetProperty(daWidth, new PropertyPath("Width"));
stb.Children.Add(daHeight); stb.Children.Add(daWidth);
mnu.menuContainer.Resources.Add("stbShowHide", stb);
mnu.stbShow = stb;
}
.....
mnu.stbShow.Begin();
Just a few explanations : our menu is a Menu object (Menu being defined in our program). It's implemented as a Border container containing a vertical StackPanel. A reference to this Border container is kept in the menuContainer field of our Menu class. We define two DoubleAnimation to increase Height and Width properties from 0 to their final values in 400 millisec. Final Height depends on number of menu items (value given by the lstMenuItems list of menu items) and final Width depends on largest width for menu items (value kept in the Width field). The two DoubleAnimation are added as children of the Storyboard object just created. The Storyboard is then added as resource of the menu container (ie the Border container).
That's it !