Skip to main content

Reversing the Z-order on a StackPanel

I had an issue the other day where I have an items control with an arbitrary number of items. I'm using Silverlight 4 and the MVVM pattern. The items to go in my ItemsControl were to be stacked horizontally, but with a negative margin such that the ones on top overlapped the ones below it. Since the items below it in the list get a higher Z-Index I had to reverse it.

I thought the solution I came up with to be nice and thought I'd share. I created the following behavior.

  1. namespace My.Application.Namespace
  2. {
  3.   using System.Windows;
  4.   using System.Windows.Controls;
  5.   using System.Windows.Interactivity;
  6.  
  7.   public class StackPanelReverseZIndex : Behavior<StackPanel>
  8.   {
  9.     /// <summary>
  10.     /// Handles the onAttached event
  11.     /// </summary>
  12.     protected override void OnAttached()
  13.     {
  14.       base.OnAttached();
  15.  
  16.       AssociatedObject.LayoutUpdated += new System.EventHandler(AssociatedObject_LayoutUpdated);
  17.     }
  18.  
  19.     protected void AssociatedObject_LayoutUpdated(object sender, System.EventArgs e)
  20.     {
  21.       int childCount = AssociatedObject.Children.Count;
  22.       foreach (FrameworkElement element in AssociatedObject.Children)
  23.       {
  24.         element.SetValue(Canvas.ZIndexProperty, childCount);
  25.         childCount--;
  26.       }
  27.     }
  28.  
  29.     /// <summary>
  30.     /// Handles the OnDetaching event
  31.     /// </summary>
  32.     protected override void OnDetaching()
  33.     {
  34.       base.OnDetaching();
  35.  
  36.       AssociatedObject.LayoutUpdated -= AssociatedObject_LayoutUpdated;
  37.     }
  38.   }
  39. }

And in order to actually apply the behavior, I added the following in XAML of the ItemsControl's panel:

  1. <StackPanel Orientation="Horizontal">
  2.   <interactivity:Interaction.Behaviors>
  3.     <myNamespace:StackPanelReverseZIndex />
  4.   </interactivity:Interaction.Behaviors>
  5. </StackPanel>