如何使用C#window store app中的箭头键移动图像?
在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;
}
答案 0 :(得分:1)
要明确定义孩子的位置,您必须使用Canvas。根据{{3}}的MSDN文档:
使用相对于“画布”区域的坐标定义可以在其中显式定位子对象的区域。
简单地将图像放入画布
<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);
}
使用Windows.UI.Xaml.Controls.Canvas和Canvas.SetLeft,您可以分别从左侧和顶部告诉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;
}