我如何在 C# 窗口商店应用程序中使用箭头键移动图像?
在 XAML 中,我放置了一个我想在箭头键上移动的图像
<Image Name ="Blue" Grid.Column="11" Source="Assets/Blue.jpg"/>
在 C# 中,我绑定(bind)了 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;
}
最佳答案
要明确定义 child 的位置,您必须使用 Canvas。根据 Windows.UI.Xaml.Controls.Canvas 的 MSDN 文档:
Defines an area within which you can explicitly position child objects, using coordinates that are relative to the Canvas area.
简单地将你的图像放在 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);
}
使用 Canvas.SetLeft和 Canvas.SetTop您可以告诉 Canvas 分别从左侧和顶部放置特定子项的位置。
编辑:要注册 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;
}
关于c# - 我如何在 C# 窗口存储应用程序中使用键移动图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25131325/