1

I need set Orientation to ListBox in C# code. I need the same result like this XAML code:

<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

I have this:

ListBox elementListBox = new ListBox();
StackPanel pomocnyStackPanel = new StackPanel();
pomocnyStackPanel.Orientation = Orientation.Horizontal;

How to add "ItemsPanel"?

Martin Gabriel
  • 69
  • 1
  • 2
  • 12
  • you can check this question, it solves a similar problem http://stackoverflow.com/questions/5755455/how-to-set-control-template-in-code – user1813 Sep 11 '13 at 09:12

2 Answers2

2

Previously could do it using FrameworkElementFactory but it's now deprecated and they suggest using XamlReader instead:

elementListBox.ItemsPanel = (ItemsPanelTemplate)XamlReader.Parse("<ItemsPanelTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><StackPanel Orientation=\"Horizontal\"/></ItemsPanelTemplate>");
dkozl
  • 32,814
  • 8
  • 87
  • 89
1

I'm not 100% sure, but I think you want something like this:

FrameworkElementFactory factory = new FrameworkElementFactory(typeof(StackPanel));
factory.SetValue(StackPanel.OrientationProperty, Orientation.Horizontal);
ItemsPanelTemplate itemsPanelTemplate = new ItemsPanelTemplate(factory);
ListBox elementListBox = new ListBox();
elementListBox.ItemsPanel = itemsPanelTemplate;

UPDATE >>>

Yep, I just tested it and it works as expected.

Sheridan
  • 68,826
  • 24
  • 143
  • 183