The program that I have creates a rectangle with a random color every time I start it. The problem is that the Rectangle isn't spawning in the center of the wpf window. I tried making stuff with
mySqaure.HorizontalAlignment = HorizontalAlignment.Center;
mySqaure.VerticalAlignment = VerticalAlignment.Center;
But that didn't work also
Brush brush = new SolidColorBrush(Color.FromRgb((byte)rand.Next(1, 255), (byte)rand.Next(1, 255), (byte)rand.Next(1, 255)));
mySqaure.Fill = brush;
mySqaure.StrokeThickness = 2;
mySqaure.Stroke = Brushes.Black;
mySqaure.Width = 200;
mySqaure.Height = 200;
myCanvas.Children.Add(mySqaure);
Content = myCanvas;
As you see I tried setting it up on the middle with margin but that doesn't work as I like.
CodePudding user response:
I based this answer off your code.
I changed a few things, first I'll give you files then explain what I did:
MainWindow.xaml
<Window x:Class="WpfApp1.MainWindow"
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"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Canvas Name="MainCanvas">
<Rectangle Name="MySquare" StrokeThickness="2" Stroke="Black" Width="200" Height="200"/>
</Canvas>
</Grid>
</Window>
MainWindow.xaml.cs
private readonly Random _random = new();
public MainWindow()
{
InitializeComponent();
Brush brush = new SolidColorBrush(Color.FromRgb(
(byte)_random.Next(255),
(byte)_random.Next(255),
(byte)_random.Next(255)));
MySquare.Fill = brush;
Canvas.SetLeft(MySquare, Width / 2.0 - MySquare.Width / 2.0);
Canvas.SetTop(MySquare, Height / 2.0 - MySquare.Height / 2.0);
}
Other than the small bits of code cleanup I did like following Microsoft Code Conventions, here is the main logic that will interest you.
Canvas.SetLeft(MySquare, Width / 2.0 - MySquare.Width / 2.0);
Canvas.SetTop(MySquare, Height / 2.0 - MySquare.Height / 2.0);
First of all, Width
and Height
are properties of the main window - this shows our total width and height.
Dividing both by 2 will give us the middle - however, we need to move the square so it is centred on the centre of the window. This is why we subtract half the width and height to align the middle of the square to the middle of the window.
Update when the window resizes
We can take this one step further, first refactor the centering to a function:
MainWindow.xaml.cs
private void CenterMySquare()
{
Canvas.SetLeft(MySquare, Width / 2.0 - MySquare.Width / 2.0);
Canvas.SetTop(MySquare, Height / 2 - MySquare.Height / 2);
}
Now the magic happens in the constructor:
CenterMySquare();
SizeChanged = (sender, args) => CenterMySquare();
Note that we centered the square on startup, but also registered an event so every time the layout changes we recenter the square. Awesome!