silverlight创建矩形,点击按钮

时间:2011-09-10 13:30:13

标签: c# silverlight

我想在C#中创建silverlight应用程序,我添加了一个按钮,我想逐个创建矩形,现在我设法创建一个矩形,但问题是我不知道如何更改要创建的下一个矩形的位置?

请帮助我希望每次点击创建一个旁边的矩形?! 谢谢 这是代码:

C#

enter code here

public MainPage()
        {
            InitializeComponent();

            Canvas c = new Canvas();

            Button b = new Button();
            Canvas.SetLeft(b, -50);
            Canvas.SetTop(b, 20);
            b.Width = 75;
            b.Height = 23;
            LayoutRoot.Children.Add(b);
            b.Click += new RoutedEventHandler(b_Click);
        }

        void b_Click(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            Rectangle rectangle = new Rectangle();
            rectangle.Fill = new SolidColorBrush(Colors.Cyan);
            Canvas.SetLeft(rectangle, 100);
            Canvas.SetTop(rectangle, 100);
            rectangle.Width = 200;
            rectangle.Height = 100;

            LayoutRoot.Children.Add(rectangle);

        }


Xaml:
<Canvas x:Name="LayoutRoot" Background="White" Height="215" Width="292">

    </Canvas>

2 个答案:

答案 0 :(得分:1)

最简单的方法是创建StackPanelWrapPanel并首先将其添加到Canvas。然后将矩形添加到

这将自动显示一行中的矩形(如果您设置Orientation Horizontal)或列(Vertical - 默认设置)。

使用更多构造(Grids等),您可以更好地控制矩形的放置位置。

答案 1 :(得分:0)

如果您要更改传递给SetLeft的{​​{1}}和SetTop方法的值。

例如,您可以执行以下操作:

Canvas

它仅更新Rectangle的double left = 100; double top = 100; void b_Click(object sender, RoutedEventArgs e) { Rectangle rectangle = new Rectangle(); rectangle.Fill = new SolidColorBrush(Colors.Cyan); Canvas.SetLeft(rectangle, left); //left is no more a constant Canvas.SetTop(rectangle, top); //top is no more a constant rectangle.Width = 200; rectangle.Height = 100; LayoutRoot.Children.Add(rectangle); //update left and top left += rectangle.Width + 10; //put some margin! if ((left + rectangle.Width) < LayoutRoot.Width) { left = 100; top += rectangle.Height + 10; } } 值,以便下一个矩形将放置在同一水平线上。它会这样做,直到左侧没有空间。只有这样它才会使left更新并使top成为第一行矩形下方的下一个矩形。它就像left = 100r1r2等等都是矩形。

r3