c# - 我如何在 C# 窗口存储应用程序中使用键移动图像

标签 c# .net windows-store-apps

我如何在 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.SetLeftCanvas.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/

相关文章:

c# - 如何在通用 Windows 应用程序中设计响应式 UI

c# - 我可以告诉 MSBuild 去哪里寻找程序集吗?

.net - 如何在 Ubuntu 上正确安装 dotnet ef?

.net - Sharepoint 2010 SPListTemplate 如何获取字段列表?

c# - 如何避免使用枚举?

c# - 如何使用具有多个 AdUnitId 的 AdControl?

c# - 合并多边形的高效算法

c# - 返回单个参数作为多映射查询的一部分

c# - 如何将 Windows 窗体 GUI 中字段的值保存到文件,然后恢复它们?

api - 如何通过 API 以编程方式在 Microsoft Store 上创建订阅加载项