我對 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-ish(可能更低)時,按鈕就會消失,直到您放大視窗大小。
我是否忽略了一個重要的代碼?
編輯: https ://gyazo.com/342b20fdbbcef2a4834ab95c37aaf30e <- 它發生的 gif
編輯 2: https ://gyazo.com/f04e1d64f9880cd01aa53f9169954377 <- 調整視窗大小的 gif
uj5u.com熱心網友回復:
在使用不同的值在設計器中玩了一會兒之后,看起來在網格中邊距優先,并且按鈕變小以適應。萬一它消失了,它的計算高度就變成了 0。
手動設定按鈕的寬度和高度,然后只更改左邊距和上邊距,同時將 rest 設定為 0:
<Grid>
<Button Margin="250,250,0,0" Width="100" Height="100">TEST</Button>
</Grid>
首先在設計器中使用值,看看什么時候發生了什么。
更好的是,不要使用元素的邊距進行布局。對于絕對定位,使用畫布:
<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));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/537382.html
標籤:C#wpf
上一篇:WPFMouseLeftButtonDown使FlowDocument無法選擇文本
下一篇:指定css空url()的正確方法