Friday, 14 November 2014

Add buttons dynamically in WPF


Add buttons to the listbox dynamically in WPF

Create a Sample WPF Application

Under MainWindow.xaml add one Listbox and wrappanel within it, where dynamically created buttons are placed.

<ListBox Background="Transparent" BorderThickness="0" Name="lstPizzaSide"
                 ScrollViewer.VerticalScrollBarVisibility="Disabled" Width="300"
                 ScrollViewer.HorizontalScrollBarVisibility="Disabled" Height="300" >
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel IsItemsHost="True" Orientation="Horizontal"  ></WrapPanel>
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
            <ListBoxItem Width="Auto" Height="Auto" HorizontalAlignment="Left"  VerticalAlignment="Top"  >
            </ListBoxItem>
        </ListBox>


In MainWindow.xaml.cs I have taken one ArrayList object where I have taken the buttons names what I wanted.

ArrayList arrPizzaSide = new ArrayList();
arrPizzaSide.Add("Whole");
arrPizzaSide.Add("Left");
 arrPizzaSide.Add("Right");
arrPizzaSide.Add("Extra");
 arrPizzaSide.Add("No");

I have taken a private method where I added the functionality of creating buttons dynamically.

 private void BindPizzaSide()
        {
            try
            {
                lstPizzaSide.Items.Clear();
                lstPizzaSide.Visibility = Visibility.Visible;
                for (int i = 0; i < arrPizzaSide.Count; i++)
                {
                    Button btnSide = new Button();
                    btnSide.Width = 150;
                    btnSide.Height = 50;
                    btnSide.Margin = new Thickness(2);
                    btnSide.Background = Brushes.BlueViolet;
                    btnSide.Foreground = Brushes.White;
                    btnSide.Content = arrPizzaSide[i].ToString();
                    btnSide.Name = "S" + (i + 1);
                    btnSide.Click += btnPizzaSide_Click;
                    btnSide.IsEnabled = true;
                    lstPizzaSide.Items.Add(btnSide);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

Note: In order to find the button individually I have given name to each button by concatenating letter "S" to it. 

Here I'm adding a click events to all the buttons

 private void btnPizzaSide_Click(object sender, RoutedEventArgs e)
        {
        //here you can write the functionality what you needed
        }

The final output as shown below



Download Code Here