Skip to main content
 首页 » 编程设计

c#之在 silverlight 中动态创建矩形

2024年02月23日12lonelyxmas

我正在尝试在 silverlight 中以编程方式创建矩形作为休闲区。

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> 

截图

请您参考如下方法:

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

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); 

结果