在silverlight中动态创建Rectangle?

时间:2011-02-28 12:00:37

标签: c# silverlight

我正试图在silverlight中以编程方式创建Rectangle作为休闲。

C#

   private Boolean Working = false;
    const int scale = 4;
    const int size = 50;
    Int32[] data = new Int32[size];
    Rectangle[] lines = new Rectangle[size];

 private void button1_Click(object sender, RoutedEventArgs e)
        {
            canvas1.Children.Clear();
            for (int i = 0; i < data.Length; i++)
            {

                data[i] = i;
                lines[i] = new Rectangle()

                {

                    Height=i*scale,
                    Width = 10,
                    StrokeThickness=5,
                    Stroke = new SolidColorBrush(Colors.Red),
                    Name=i.ToString(),
                };

                canvas1.Children.Add(lines[i]);
            }
        }

现在问题是所有矩形都是以相同的高度和宽度创建的?。

XAML

<UserControl x:Class="SilverlightApplication1.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="500"  d:DesignWidth="500">

    <Canvas x:Name="canvas2" Background="White">
        <Canvas x:Name="canvas1" Background="White"></Canvas>
        <Button Content=" Generate"  Height="38"  Name="button1"  Width="75"  Click="button1_Click" Margin="0,352,245,24" HorizontalAlignment="Right" Canvas.Left="12" Canvas.Top="85" />
        <Button Content="Shuffle" Height="38" HorizontalAlignment="Left"  Name="button2" Margin="12,352,0,24" Click="button2_Click_1" Canvas.Left="81" Canvas.Top="85" Width="71" />
        <Button Canvas.Left="181" Canvas.Top="437" Content="Bubble Sort" Height="38" Name="button3" Width="109" Click="button3_Click" />
    </Canvas>

</UserControl>

截图

enter image description here

1 个答案:

答案 0 :(得分:4)

实际上,一切正常。所有矩形都有不同的高度。但你忘了移动它们,所以它们开始重叠。更改一些代码,你会看到:

lines[i] = new Rectangle()
{
    Height = i * scale,
    Width = 10,
    StrokeThickness = 5,
    Stroke = new SolidColorBrush(Colors.Red),
    Name = i.ToString(),
};
lines[i].Margin = new Thickness(11 * i, 0, 0, 0);

结果

Screenshot