我为我的英语语法弱点道歉。我尝试在 WPF 网格中绘制一个矩形。我画了它,但在网格的右侧和底部看不到这个矩形。我应该怎么办?这是我的 XAML 和代码。
< 窗口 x:Class="DrawCircle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
MouseLeftButtonUp="window_MousLefteUp" MouseRightButtonUp="window_MouseRightButtonUp"
MouseMove="Grid_MouseMove"
MouseDown="Grid_MouseDown" >
<Grid x:Name="window" Margin="0,0,0,0" Background="PaleGreen" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" ClipToBounds="False">
<Grid.RenderTransform>
<TransformGroup>
<ScaleTransform x:Name="scaleTransform1" ScaleX="0.5" ScaleY="0.5" />
<TranslateTransform x:Name="translateTransform1" X="0" Y="0" />
</TransformGroup>
</Grid.RenderTransform>
</Grid>
它的背后代码是:
public partial class MainWindow : Window
{
bool cornerPointed = false;
Point corner1;
Rectangle myRectangle;
public MainWindow()
{
InitializeComponent();
myRectangle = new Rectangle();
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.VerticalAlignment = VerticalAlignment.Top;
myRectangle.Stroke = Brushes.Red;
window.Children.Add(myRectangle);
}
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
cornerPointed = true;
corner1 = new Point(e.GetPosition(this.window).X, e.GetPosition(this.window).Y);
myRectangle.Margin = new Thickness(corner1.X, corner1.Y, 0, 0);
}
private void Grid_MouseMove(object sender, MouseEventArgs e)
{
if (cornerPointed == true)
{
Point corner2 = e.GetPosition(this.window);
myRectangle.Margin = new Thickness(System.Math.Min(corner1.X, corner2.X),
System.Math.Min(corner1.Y, corner2.Y),
0, 0);
myRectangle.Width = Math.Abs(e.GetPosition(this.window).X - corner1.X);
myRectangle.Height = Math.Abs(e.GetPosition(this.window).Y - corner1.Y);
}
}
private void window_MousLefteUp(object sender, MouseButtonEventArgs e)
{
cornerPointed = false;
myRectangle = new Rectangle();
myRectangle.HorizontalAlignment = HorizontalAlignment.Left;
myRectangle.VerticalAlignment = VerticalAlignment.Top;
myRectangle.Stroke = Brushes.Red;
window.Children.Add(myRectangle);
}
}