-1

I am able to add multiple button controls to Grid panel and Stack panel, but i am not able to add it Canvas panel is there any way to do it?

Please find below code for Grid and Stack.

 foreach (string subfolder in Directory.GetDirectories(path))
        {
            ToggleButton btn = new ToggleButton();
            btn.Name = "btn" + column.ToString();
            btn.Content = subfolder.Substring(subfolder.LastIndexOf("\\") + 1);
            btn.Tag = subfolder;
            btn.Margin = new Thickness(15, 15, 10, 0);
            btn.Width = 200;
            btn.Height = 50;
            btn.Checked += btn_Checked;
            btn.Unchecked += btn_Unchecked;
            btn.HorizontalAlignment = HorizontalAlignment.Left;                
            GridPanel.Children.Add(btn);//Adding controls to Grid Panel
       }

How to do same for canvas Panel? Thanks in advance.

Anjali
  • 1,680
  • 4
  • 26
  • 48
  • 2
    Better: do not create UI elements in code behind. Use an ItemsControl with the ToggleButton in its ItemTemplate, and the desired Panel in the ItemsControl's ItemsPanel. – Clemens Nov 07 '17 at 11:37
  • @Clemens, I am new to WPF. can you share a link? how to add controls dynamically to ItemsControl's – Anjali Nov 07 '17 at 12:09
  • @Anjali https://stackoverflow.com/questions/7177432/how-to-display-items-in-canvas-through-binding – FoggyFinder Nov 07 '17 at 12:14
  • 1
    I've googled "wpf itemscontrol button" for you: https://rachel53461.wordpress.com/2011/09/17/wpf-itemscontrol-example/ – Clemens Nov 07 '17 at 12:14
  • @Anjali just a note - there the [WPF chat room](https://chat.stackoverflow.com/rooms/18165/wpf) where you can get help too. – FoggyFinder Nov 07 '17 at 12:19

1 Answers1

1

You add an element to a Canvas the exact same way. Just set the Canvas.Left and Canvas.Top attached properties of the element to specify its position within the Canvas:

Canvas.SetLeft(btn, 10.0);
Canvas.SetTop(btn, 15.0);
theCanvas.Children.Add(btn);

If you don't see the elements, you should make sure that you have given the Canvas some size:

<Canvas x:Name="theCanvas" Width="100" Height="100" />
mm8
  • 163,881
  • 10
  • 57
  • 88