Tuesday, August 30, 2016

Changing the ZIndex of a XAML Element using a Storyboard

One of my current projects has two XAML elements moving in 3D and as the  second element eclipsed the first element the ZIndex had to be changed so the second element would now appear in front of the first. 

Lots of searching later (and quite a few articles saying that it was not possible) I came up with a XAML based Storyboard that worked, but since I needed to build the Storyboard programmatically, I needed to convert it to C# code.

This is what I came up with:

Code Snippet – CreateZIndexStoryboard
  1. private Storyboard CreateZIndexStoryboard(FrameworkElement fromElement, int newZIndex)
  2. {
  3.     var myZIndexStoryboard = new Storyboard();
  4.     var myZIndexAnimation = new ObjectAnimationUsingKeyFrames();       
  5.     var myZIndexKeyFrame = new DiscreteObjectKeyFrame
  6.     {
  7.         Value = newZIndex,
  8.         KeyTime = TimeSpan.FromMilliseconds(AnimationLength/2)
  9.     };
  11.     myZIndexAnimation.KeyFrames.Add(myZIndexKeyFrame);
  13.     myZIndexStoryboard.Children.Add(myZIndexAnimation);
  15.     Storyboard.SetTarget(myZIndexAnimation, fromElement);
  16.     Storyboard.SetTargetProperty(myZIndexAnimation, "(Canvas.ZIndex)");
  18.     return myZIndexStoryboard;
  19. }

One of the main points of difference between Silverlight and Windows Universal XAML is that setting the target property on the storyboard, ie. Storyboard.SetTargetProperty is that in silverlight you would set the path to the property by creating a new PropertyPath object.  With Windows Universal XAML you using a binding to a property using a string with binding syntax.

No comments: