如何在WPF中向画布添加多个按钮?

时间:2017-11-07 11:25:37

标签: c# wpf canvas grid togglebutton

我能够为Grid面板和Stack面板添加多个按钮控件,但是我无法添加它Canvas面板有什么方法可以做到吗?

请在下面找到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
       }

如何为帆布面板做同样的事情? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您以完全相同的方式向Canvas添加元素。只需设置元素的Canvas.LeftCanvas.Top附加属性,以指定其在Canvas中的位置:

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

如果你没有看到这些元素,你应该确保给出Canvas一些大小:

<Canvas x:Name="theCanvas" Width="100" Height="100" />