为什么按钮总是越界?(WPF应用程序)



我对c#很陌生,所以预计错误/冗长的代码没有好的理由。

所以我在玩WPF应用程序,因为我想知道如何使一个按钮移动时悬停在它-我设法做到了,但现在它越界?

XAML代码:

<Window x:Class="Opdracht7.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:Opdracht7"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button x:Name="klikmij" Content="Click me!" MouseEnter="onMouseEnter" Click="onMouseClick" HorizontalAlignment="Center" VerticalAlignment="Center" RenderTransformOrigin="-0.989,-0.519" Height="33" Width="68"/>
</Grid>
</Window>
c#代码转储:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static System.Net.Mime.MediaTypeNames;
namespace Opdracht7
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private void onMouseEnter(object sender, MouseEventArgs e)
{
Random rnd1 = new Random();
int value1 = rnd1.Next(0, 250);
int value2 = rnd1.Next(0, 250);
int value3 = rnd1.Next(0, 250);
int value4 = rnd1.Next(0, 250);

Debug.WriteLine(value1);
Debug.WriteLine(value2);
Debug.WriteLine(value3);
Debug.WriteLine(value4);
klikmij.Margin = new Thickness(value1,value2, value3, value4);
}
private void onMouseClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("Congratulations! You won nothing!");
}
public MainWindow()
{
InitializeComponent();
}
}
}

我设置了从0到250的随机范围,因为当我将其调整为窗口的实际高度和宽度时,它会更快地超出界限。由于一些奇怪的原因,当它超过230左右(可能更低),按钮就会消失,直到你扩大窗口大小。

我是不是忽略了一段重要的代码?

编辑:https://gyazo.com/342b20fdbbcef2a4834ab95c37aaf30e <-发生的GIF

编辑2:https://gyazo.com/f04e1d64f9880cd01aa53f9169954377 <-调整窗口大小的GIF

在设计器中使用不同的值后,看起来在网格中边距优先,并且按钮变得更小以适应。如果它消失了,它的计算高度就变成了0。

手动设置按钮的宽度和高度,然后只更改左侧和顶部边距,同时将rest设置为0:

<Grid>
<Button Margin="250,250,0,0" Width="100" Height="100">TEST</Button>
</Grid>

先在设计器中设置数值,看看会发生什么。

最好不要使用元素的页边距进行布局。对于绝对定位,使用Canvas:

<Grid>
<Canvas>
<Button x:Name="klikmij" Content="Click me!" 
MouseEnter="onMouseEnter" Click="onMouseClick"
Height="33" Width="68"/>
</Canvas>
</Grid>

后面有代码:

private readonly Random rnd = new Random();
private void onMouseEnter(object sender, MouseEventArgs e)
{
Canvas.SetLeft(klikmij, rnd.Next(0, 250));
Canvas.SetTop(klikmij, rnd.Next(0, 250));
}

最新更新