Search code examples
c#windows-phone-8stackpanel

Wp8 how to add items in the stackpanel dynamically


I need help for item add in the stackpanel. My item name is "kanal" its wp8 imagebutton item. Its my codes

public mainpage()
{
    InitializeComponent();
    foreach (var kanal in MainPage.kanalllarstatik)
    {
        mystackpanel.Children.Add(kanal);
    }           
}

I need add 130x130 pixel 3 button items per line like this:

Its my app and button size is 130x130 pixel


Solution

  • Stackpanel only put one element per line so you need to put a horizontal stackpanel (in each line) and then add to it the three elements.

    If you want a 130x130 control, you should use:

    kanel.Height=130;
    kanal.Width =130;
    

    Code example

    Test Data

       List<Button> buttons = new List<Button>();
            for (int i = 0; i < 16; i++)
            {
                buttons.Add(new Button
                {
                    Height = 130,
                    Width = 130,
                    Content = new TextBlock
                    {
                        Text = i.ToString()
                    }
                });
            }
    

    Algorithm

    StackPanel horizontalStackPanel = new StackPanel
                {
                    Orientation = Orientation.Horizontal
                };
    
                foreach (Button button in buttons)
                {
                    horizontalStackPanel.Children.Add(button);
                    if (horizontalStackPanel.Children.Count == 3) //new line
                    {
                       myStackPanel.Children.Add(horizontalStackPanel);
                        horizontalStackPanel = new StackPanel
                        {
                            Orientation = Orientation.Horizontal
                        };
                    }
    
                }
                myStackPanel.Children.Add(horizontalStackPanel);
    

    XAML
    <StackPanel x:Name="myStackPanel"></StackPanel>

    Result

    enter image description here

    I hope that this can help you.