Pages

Wednesday, 8 February 2012

ItemsControl horizontal content layout

ItemsControl lays out its content vertically by default. To arrange it horizontally we set the Orientation of the StackPanel in the ItemsPanelTemplate. In XAML like this:
<ItemsControl>
   <ItemsControl.ItemsPanel>
      <ItemsPanelTemplate>
         <StackPanel Orientation="Horizontal"/>
      </ItemsPanelTemplate>
   </ItemsControl.ItemsPanel>
</ItemsControl>
And in C#, working from the deepest levels outward, like this:
FrameworkElementFactory factoryPanel =
   new FrameworkElementFactory(typeof(StackPanel));
factoryPanel.SetValue(
   StackPanel.OrientationProperty,
   Orientation.Horizontal);

ItemsPanelTemplate template = new ItemsPanelTemplate();
template.VisualTree = factoryPanel;

ItemsControl itemsControl = new ItemsControl();
itemsControl.ItemsPanel = template;

No comments: