我如何移动图像与键在c#窗口商店应用程序
本文关键字:窗口 应用程序 图像 何移动 移动 | 更新日期: 2023-09-27 18:16:19
如何在c#窗口商店应用程序中使用箭头键移动图像?
在XAML中,我放置了一个图像,我想用方向键移动
<Image Name ="Blue" Grid.Column="11" Source="Assets/Blue.jpg"/>
在c#中,我绑定Keydown事件,但我的代码移动图像上/下/右/左不工作。
public MainPage()
{
this.InitializeComponent();
KeyDown += new KeyEventHandler(MainPage_KeyDown);
}
private void MainPage_KeyDown(object sender, KeyRoutedEventArgs e)
{
if (e.Key == Windows.System.VirtualKey.Right)
Blue.HorizontalAlignment += 30;
else if (e.Key == Windows.System.VirtualKey.Left)
Blue.HorizontalAlignment -= 1;
else if (e.Key == Windows.System.VirtualKey.Up)
Blue.VerticalAlignment += 1;
else if (e.Key == Windows.System.VirtualKey.Down)
Blue.VerticalAlignment -= 1;
}
要明确定义孩子的位置,你必须使用Canvas。根据MSDN文档Windows.UI.Xaml.Controls.Canvas:
定义一个区域,您可以使用相对于Canvas区域的坐标在其中显式地定位子对象。
简单的把你的图像放在画布
<Canvas>
<Image x:Name="BlueImage" Source="Assets/Blue.png" />
</Canvas>
可以使用下面的c#代码来上下左右移动图像。
private void HandleKeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
{
if (args.VirtualKey == Windows.System.VirtualKey.Right)
Canvas.SetLeft(BlueImage, Canvas.GetLeft(BlueImage) + 30);
else if (args.VirtualKey == Windows.System.VirtualKey.Left)
Canvas.SetLeft(BlueImage, Canvas.GetLeft(BlueImage) - 30);
else if (args.VirtualKey == Windows.System.VirtualKey.Up)
Canvas.SetTop(BlueImage, Canvas.GetTop(BlueImage) - 30);
else if (args.VirtualKey == Windows.System.VirtualKey.Down)
Canvas.SetTop(BlueImage, Canvas.GetTop(BlueImage) + 30);
}
使用画布。SetLeft和Canvas。SetTop你可以告诉Canvas从左到上分别放置特定子元素的位置。
EDIT:要注册KeyDown事件,您必须重写OnNavigatedFrom和OnNavigatedTo方法。
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
Window.Current.CoreWindow.KeyDown -= HandleKeyDown;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
Window.Current.CoreWindow.KeyDown += HandleKeyDown;
}