Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在Silverlight中动态地将控件放置在画布上?_C#_Silverlight_Canvas - Fatal编程技术网

C# 如何在Silverlight中动态地将控件放置在画布上?

C# 如何在Silverlight中动态地将控件放置在画布上?,c#,silverlight,canvas,C#,Silverlight,Canvas,我正在尝试将已创建的控件放置在我的画布上。其想法是能够动态地添加它们。如在按钮上单击或在调度计时器的末尾单击。我有以下内容,但它不起作用: FirstCircleControl mc = new FirstCircleControl(); Canvas.SetLeft(mc, 100); Canvas.SetTop(mc, 100); 我没有看到任何控件出现…您需要先将控件添加到画布中 yourCanvas.Children.Add(mc) 将控件放置在画布或网格中需

我正在尝试将已创建的控件放置在我的
画布上。其想法是能够动态地添加它们。如在按钮上单击或在
调度计时器的末尾单击。我有以下内容,但它不起作用:

    FirstCircleControl mc = new FirstCircleControl();
    Canvas.SetLeft(mc, 100);
    Canvas.SetTop(mc, 100);

我没有看到任何控件出现…

您需要先将控件添加到
画布中

yourCanvas.Children.Add(mc)

将控件放置在画布或网格中需要两个步骤

  • 将控件添加到容器的子集合
  • 设置控件在容器中的位置
  • 你已经迈出了第二步,但却错过了第一步

    用于画布

    Button childButton = new Button();
    LayoutCanvas.Children.Add(childButton);
    Canvas.SetLeft(childButton, 120);
    Canvas.SetTop(childButton, 120);
    
    对于网格

    Button childButton = new Button();
    LayoutGrid.Children.Add(childButton);
    Grid.SetRow(childButton, 2);
    Grid.SetColumn(childButton, 2);
    
    另一种(在某些情况下更容易)方法是从
    ui元素
    端:

        (controlItem as UIElement).SetValue(Canvas.TopProperty, topVal);
        (controlItem as UIElement).SetValue(Canvas.LeftProperty, left);
    

    谢谢你,布拉德。我注意到我还需要设置控件的宽度和高度以使其可见。