'how to add ListView with orientation as horizontal from code behind in uwp?

I have to achieve this syntax from code behind how can I do that

    <ListView>
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <ItemsStackPanel Orientation="Horizontal" 
                     />
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
    </ListView>

in general how can I achieve property element syntax from code behind in uwp?



Solution 1:[1]

how to add ListView with orientation as horizontal from code behind in uwp?

For making ItemsPanelTemplate in the code behind, you could parse ItemsPanelTemplate string and then pass it to ListView's ItemsPanel.

private void ApplyItemsStackPanelAsItemsPanel(ItemsControl itemsControl)
{

    var itemsPanelTemplateXaml =
        $@"<ItemsPanelTemplate xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                          xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
           <ItemsStackPanel Orientation='Horizontal'/>
       </ItemsPanelTemplate>";

    itemsControl.ItemsPanel = (ItemsPanelTemplate)XamlReader.Load(itemsPanelTemplateXaml);

}

Usage

private void BuildListView()
{
    var listview = new ListView();
    ApplyItemsStackPanelAsItemsPanel(listview);
    listview.ItemsSource = new string[] { "1", "2", "3", "4" };
    this.Content = listview;
}

Solution 2:[2]

You can achieve it this way.

<ListView x:Name="AwesomeListView" ItemsSource="{x:Bind Items}">
    <!--
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsStackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    -->
</ListView>
public sealed partial class MainPage : Page
{
    public List<int> Items { get; set; } = new List<int>() { 1, 2, 3, 4, 5 };

    public MainPage()
    {
        this.InitializeComponent();

        this.AwesomeListView.ItemsPanel = CreateItemsPanelTemplate(Orientation.Horizontal);
    }

    ItemsPanelTemplate CreateItemsPanelTemplate(Orientation orientation)
    {
        string xamlString =
            $@"<ItemsPanelTemplate
                    xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
                    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'>
                    <ItemsStackPanel Orientation='{orientation}' />
                </ItemsPanelTemplate>";

        return (ItemsPanelTemplate)XamlReader.Load(xamlString);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nico Zhu - MSFT
Solution 2 Andrew KeepCoding