Originally published on my old Charteris blog

Whilst working on my graph control a couple of nights ago I found that I needed to have the values of my X axis stacked with the first item at the bottom and the last at the top. I was using the ItemsPanel default of a StackPanel, this StackPanel element does give you some control over how the items are stacked using the Orientation property. Unfortunately that only goes as far as saying “stack horizontally or vertically”.

My first thought was create a custom implementation of the StackPanel adding the ability to invert the stack for either orientation. Then I remembered DockPanel and how it is similar in many ways to StackPanel. The main difference between the two when it comes to stacking their respective children is in how they size them. StackPanel will size in the direction of the orientation to a size of infinity whereas DockPanel will size to the space available. The trick to using the DockPanel to get my inverted stack was to dock all the items to the bottom.

I changed the ItemsControl XAML for the x axis to the following

<ItemsControl Name="YAxisItems"

                  ItemTemplate="{StaticResource YAxisItemTemplate}"

                  ItemsSource="{TemplateBinding YAxis}">

      <ItemsControl.ItemsPanel>

        <ItemsPanelTemplate>

          <DockPanel LastChildFill="False"/>

        </ItemsPanelTemplate>

      </ItemsControl.ItemsPanel>

        <ItemsControl.ItemContainerStyle>

          <Style>

            <Setter Property="DockPanel.Dock" Value="Bottom"></Setter>

          </Style>

        </ItemsControl.ItemContainerStyle>

    </ItemsControl>

  • ItemsControl.ItemsPanel lets me specify a Dockpanel as the main containing panel rather tha the default StackPanel.
  • ItemsControl.ItemContainerStyle lets me set propeties on the ItemContainer and it is here that I set DockPanel.Dock=”Bottom”.

The containers that are available out-of-the-box cover a fairly decent set of layout styles and I was glad I remembered DockPanels bottom up stacking before I went off to develop InvertableStackPanel.

Here is a simple example of inverting the stack with a DockPanel and showing how they size differently.