Z-Index in Silverlight / WPF

I was working on some animations the other day. To make a long story short, I had a Listbox in a Grid that needed to flip. Think of a page-flip like animation. Of course, on the other side of the page there is another page. Otherwise, why bother turning it?

The basic techniques for this is quite simple. I defined two listboxes, one was turned around by using the PlaneProjection and set the Y-Rotation to 180.0. In the grid that housed the listboxes I put both listboxes on top of each other, the first page defined last so it would be on top.

Now I had to turn both listboxes. I defined two double animations, put them in a storyboard and watched what happened. The first half of the animation looked great. But then, as the angle passed the 90 degrees, I saw the first page, but mirrored. I expected to see the second listbox. But of course things don’t work that way. The z-order in which they were defined meant that the second listbox was behind the first and it stayed there, no matter what the animation did.

So I had to do it another way. I broke the animation in two parts. One was to first flip the listboxes 90 degrees, then stop and change the z-order of the listboxes so that number 2 would be on top of number one. Then another animation would kick on to complete the turn to 180 degrees (The moment I finished this code I realized I was being silly: there was no need for two listboxes at all, just one would be enough, but that’s besides the point).

But… how to change the z-order in a Grid? I knew that Canvas has the ZIndex property, but Grid hasn’t. I could move to using Canvas of course, but then I would loose the advantages and flexibility of the Grid.

After a bit of trying out the answer was pretty easy, but strange nonetheless: you can specify a z-order although you don’t use the Canvas but have another panel acting as a container instead!

firstStoryboard.Completed += (s, args) =>
{    
Canvas.SetZIndex(topListbox, 1);    
Canvas.SetZIndex(bottomListbox, 2);
     secondStoryboard.Begin(); }; firstStoryboard.Begin();

So apparently, even though the Grid doesn’t have a ZIndex property, and it’s parent Panel doesn’t either, you can still do this and it will work.

I wonder what happens under the covers.

Tags van Technorati: ,

Print | posted @ Saturday, May 21, 2011 12:18 AM

Comments on this entry:

No comments posted yet.

Post A Comment
Title:
Name:
Email:
Comment:
Verification: