Search code examples
c#wpfitemscontrol

Align items in ItemsControl horizontally (no xaml)


I am looking for a way to set the alignment of the items in an ItemsControl so that they are not positioned from top to bottom (default) but from left to right.

I thought there is a property that can easily be set, like

ItemsControl crtl = new ItemsControl;
...
ctrl.ContentAlignment = ContentAlignment.Horizontal; // does not exist

But it seems this is not the case. There are countless examples in XAML out there to achieve this (usually they use styles or templates or something like that), but I found none in plain C# code. And I don't know how to convert the xaml statements to C# code either.

Can anyone give a hint?


Solution

  • Let`s try to use property Orientation like in here: ItemsControl with horizontal orientation‌​‌​h-horizontal-orien‌​ta‌​tion

    Here is an example:

     var itemsControl = new ItemsControl();    
     var factoryPanel = new FrameworkElementFactory(typeof(StackPanel));
     factoryPanel.SetValue(Panel.IsItemsHostProperty, true);
    
     factoryPanel.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);    
     var template = new ItemsPanelTemplate {VisualTree = factoryPanel};       
     itemsControl.ItemsPanel = template;