我的程式每次啟動時都會創建一個帶有隨機顏色的矩形。問題是矩形沒有在 wpf 視窗的中心生成。我試著用
mySqaure.HorizontalAlignment = HorizontalAlignment.Center;
mySqaure.VerticalAlignment = VerticalAlignment.Center;
但這也不起作用
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;
如您所見,我嘗試將其設定在帶有邊距的中間,但這并不像我喜歡的那樣作業。
uj5u.com熱心網友回復:
我根據你的代碼給出了這個答案。
我改變了一些東西,首先我會給你檔案然后解釋我做了什么:
主視窗.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>
主視窗.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);
}
除了我喜歡遵循Microsoft 代碼約定的少量代碼清理之外,這里是您會感興趣的主要邏輯。
Canvas.SetLeft(MySquare, Width / 2.0 - MySquare.Width / 2.0);
Canvas.SetTop(MySquare, Height / 2.0 - MySquare.Height / 2.0);
首先,Width和Height是在主視窗的性能-這顯示了我們的總寬度和高度。
將兩者除以 2 將得到中間位置 - 但是,我們需要移動正方形,使其以視窗中心為中心。這就是為什么我們減去一半的寬度和高度以將正方形的中間對齊到視窗的中間。
當視窗調整大小時更新
我們可以更進一步,首先將中心重構為一個函式:
主視窗.xaml.cs
private void CenterMySquare()
{
Canvas.SetLeft(MySquare, Width / 2.0 - MySquare.Width / 2.0);
Canvas.SetTop(MySquare, Height / 2 - MySquare.Height / 2);
}
現在魔術發生在建構式中:
CenterMySquare();
SizeChanged = (sender, args) => CenterMySquare();
請注意,我們在啟動時將正方形居中,但也注冊了一個事件,因此每次布局更改時,我們都會重新調整正方形。驚人的!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341192.html
上一篇:創建一個相互下方的矩形
