如何用方向键在网格中移动图像

本文关键字:移动 图像 网格 何用 方向 | 更新日期: 2023-09-27 18:16:06

我在WPF应用程序中做游戏…对于好奇的人来说,它是青蛙。我想用方向键在网格中移动一个图像。我的代码:

private void image_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Right)
            {
                Grid.SetRow(frog, 0);
                Grid.SetColumn(frog, 1);
            }
            else if (e.Key == Key.Up)
            {
                Grid.SetRow(frog, 1);
                Grid.SetColumn(frog, 0);
            }
            else if (e.Key == Key.Down)
            {
                Grid.SetRow(frog, -1);
                Grid.SetColumn(frog, 0);
            }
            else if (e.Key == Key.Left)
            {
                Grid.SetRow(frog, 0);
                Grid.SetColumn(frog, -1);
            }
        }

我的图像是"青蛙"。我在这部分代码中使用了KeyDown事件…这是我的XAML代码:

<Image Name="frog" Source="images/18953.png" Grid.Column="3" HorizontalAlignment="Center" Height="35" Grid.Row="9" VerticalAlignment="Center" Width="35" KeyDown="image_KeyDown"/>

但是什么都没用。我错在哪里?

如何用方向键在网格中移动图像

您的图像需要是Focusable,在MouseDown中设置焦点,然后您将收到关键事件。

<Image Name="frog"
       Focusable="True"
       Source="..."
       KeyDown="Frog_OnKeyDown"
       MouseDown="Frog_OnMouseDown"></Image>

后面的代码
private void Frog_OnKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Right)
    {
        if (Grid.GetColumn(frog) <= Grid.ColumnDefinitions.Count - 1)
            Grid.SetColumn(frog, Grid.GetColumn(frog) + 1);
    }
    else if (e.Key == Key.Up)
    {
        if (Grid.GetRow(frog) > 0)
            Grid.SetRow(frog, Grid.GetRow(frog) - 1);
    }
    else if (e.Key == Key.Down)
    {
        if (Grid.GetRow(frog) <= Grid.RowDefinitions.Count - 1)
            Grid.SetRow(frog, Grid.GetRow(frog) + 1);
    }
    else if (e.Key == Key.Left)
    {
        if (Grid.GetColumn(frog) > 0)
            Grid.SetColumn(frog, Grid.GetColumn(frog) - 1);
    }
}
private void Frog_OnMouseDown(object sender, MouseButtonEventArgs e)
{
    frog.Focus();
}