WrapPanel control is a panel that positions child elements in sequential position from left to right, breaking content to the next line at the edge of the containing box.
You can explicitly set the width of the WrapPanel so that a maximum of three rectangles fit in a row.
Xaml:
<StackPanel>
<Button Content="click" Height="30" Width="100" Click="Button_Click" />
<WrapPanel Name="canvasWrapPanel" Width="250" />
</StackPanel>
Codebehind:
private void Button_Click(object sender, RoutedEventArgs e)
{
for (var i = 0; i < 5; i++)
{
canvasWrapPanel.Children.Add(new Rectangle
{
Width = 50,
Height = 50,
StrokeThickness = 2,
Name="box"+i.ToString(),
Stroke = new SolidColorBrush(Colors.Black),
Margin = new Thickness(15)
});
}
}
Or you can use Canvas instead of WrapPanel.
<Canvas x:Name="canvas" >
</Canvas>
Codebehind:
int width = 50;
int height = 50;
int top ;
int left;
for (int x = 0; x < 3; x++)
{
for(int y = 0; y < 3; y++)
{
Rectangle rec = new Rectangle()
{
Width = width,
Height = height,
Stroke = Brushes.Black,
StrokeThickness = 2,
};
left=2*x*width+x;
top=height*2 * y +y;
canvas.Children.Add(rec);
Canvas.SetTop(rec, top);
Canvas.SetLeft(rec, left);
}
}
The result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our [documentation][5] to enable e-mail notifications if you want to receive the related email notification for this thread.
[5]: https://learn.microsoft.com/en-us/answers/articles/67444/email-notifications.html