当用户双击鼠标时,我正在画布上移动一个矩形。代码中有一个错误导致矩形离开屏幕。我怎样才能阻止这种情况发生?
这是我的 XAML:
<Window x:Class="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" SnapsToDevicePixels="True" BorderThickness="1" ScrollViewer.HorizontalScrollBarVisibility="Visible" WindowStyle="ToolWindow" MouseDoubleClick="mouse_dblClick">
<Canvas Height="350" Width="525" SnapsToDevicePixels="True">
<Rectangle Canvas.Left="100" Canvas.Top="10" x:Name="Rect" Fill="#FFF4F4F5" HorizontalAlignment="Left" Height="47" Stroke="Black" VerticalAlignment="Top" Width="247" Margin="128,182,0,0" RenderTransformOrigin="-2.021,-1.247"/>
</Canvas>
<Window.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black" Offset="0"/>
<GradientStop Color="#FF51AC3D" Offset="1"/>
</LinearGradientBrush>
</Window.Background>
</Window>
这是我的 C# 代码:
private void mouse_dblClick(object sender, MouseButtonEventArgs e)
{
this.Title = string.Format("{0}",e.GetPosition(this).ToString());
Canvas.SetLeft(this.Rect, e.GetPosition(this).Y);
Canvas.SetTop(this.Rect, e.GetPosition(this).X);
}