我正在使用C#和Visual Studio制作WPF应用程序,当鼠标悬停在窗口上时,我需要一个按钮来跳转到窗口中的随机位置。然后,当你再次将鼠标悬停在它上面时,我需要做同样的事情。我也不需要动画,只是为了跳到那里。
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void butNo_MouseEnter(object sender, MouseEventArgs e)
{
}
}
我试过这个,但它不起作用,也是一个动画:
<Button.Triggers>
<EventTrigger RoutedEvent="Button.Click">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation From="0" To="100" Duration="0:0:2" Storyboard.TargetProperty="(Canvas.Left)" AutoReverse="False" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
非常感谢任何帮助,谢谢。
编辑:
试过这个,但'位置'在VS中附带错误代码CS1061。
private void butNo_MouseEnter(object sender, MouseEventArgs e)
{
Random x = new Random();
Point pt = new Point(int.Parse(x.Next(200).ToString()), int.Parse(x.Next(250).ToString()));
butNo.Location = pt;
}
答案 0 :(得分:0)
我真的不喜欢为人们做家庭作业问题,但我在工作中很无聊,所以你走了。
您只需使用边距,并将Left和Top值更新为网格高度/宽度内的随机数,以便它不会超出视图范围。
另外,请务必使用 IsTabStop =“False”,否则,您可以选中它并仍然点击它。
所以,对于使用codebehind的最简单的情况:
XAML:
<Window x:Class="mousemove.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">
<Grid x:Name="Grid1">
<Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="0,0,0,0" Name="button1" Width="75" MouseEnter="button1_MouseEnter" IsTabStop="False"/>
</Grid>
MainWindow.xaml.cs
private void button1_MouseEnter(object sender, MouseEventArgs e)
{
int maxLeft = Convert.ToInt32(Grid1.ActualWidth - button1.Width);
int maxTop = Convert.ToInt32(Grid1.ActualHeight - button1.Height);
Random rand = new Random();
button1.Margin = new Thickness(rand.Next(maxLeft), rand.Next(maxTop), 0, 0);
}
答案 1 :(得分:0)
以下是使用Canvas
和动画的解决方案。
<Canvas Name="cnv">
<Button Name="btn"
Content="Click Me!"
IsTabStop="False"
Canvas.Left="0"
Canvas.Top="0"
MouseEnter="Button_MouseEnter"/>
</Canvas>
代码隐藏:
Random rnd = new Random();
private void Button_MouseEnter(object sender, MouseEventArgs e)
{
//Work out where the button is going to move to.
double newLeft = rnd.Next(Convert.ToInt32(cnv.ActualWidth - btn.ActualWidth));
double newTop = rnd.Next(Convert.ToInt32(cnv.ActualHeight - btn.ActualHeight));
//Create the animations for left and top
DoubleAnimation animLeft = new DoubleAnimation(Canvas.GetLeft(btn), newLeft, new Duration(TimeSpan.FromSeconds(1)));
DoubleAnimation animTop = new DoubleAnimation(Canvas.GetTop(btn), newTop, new Duration(TimeSpan.FromSeconds(1)));
//Set an easing function so the button will quickly move away, then slow down
//as it reaches its destination.
animLeft.EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseOut };
animTop.EasingFunction = new CubicEase() { EasingMode = EasingMode.EaseOut };
//Start the animation.
btn.BeginAnimation(Canvas.LeftProperty, animLeft, HandoffBehavior.SnapshotAndReplace);
btn.BeginAnimation(Canvas.TopProperty, animTop, HandoffBehavior.SnapshotAndReplace);
}
这里有一个gif。