WPF使用箭头键移动图像

时间:2017-06-09 21:53:35

标签: c# wpf xaml

您好我正在尝试制作一个蛇形游戏,但我不想使用一个形状,而是想用头部的图像和其他身体的其他图像。 我是WPF的新手,我发现的所有教程都只使用形状。 我现在想要做的是使用箭头键移动我的图像,最后在我得到工作后检测与板上其他图像的碰撞。 这是我的主窗口xaml代码。它包含一个我想要移动的简单图像(DogeIcon),如上所述,另一个图像(cat)是一个障碍。

<Window x:Class="DogeSNake.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:DogeSNake"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Image Name="DogeIcon" HorizontalAlignment="Left" Height="64" Margin="33,27,0,0" VerticalAlignment="Top" Width="64" Source="media/doge.png" MouseEnter="RectangleMouseEnter" />
    <Image Name="CatIcon" HorizontalAlignment="Left" Height="40" Margin="445,247,0,0" VerticalAlignment="Top" Width="40" Source="media/cat.png" />
</Grid>

1 个答案:

答案 0 :(得分:0)

你需要的不是网格而是画布......

<Window x:Class="DogeSNake.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:DogeSNake"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" FocusManager.FocusedElement="{Binding ElementName=MyCanvas}">
    <Canvas Name="MyCanvas" KeyDown="Canvas_KeyDown" Focusable="True" >
            <Image Name="DogeIcon" Canvas.Left="10" Canvas.Top="10" HorizontalAlignment="Left" Height="64" Margin="0" VerticalAlignment="Top" Width="64" Source="media/doge.png" MouseEnter="RectangleMouseEnter"/>
            <Image Name="CatIcon"  Canvas.Left="200" Canvas.Top="200" HorizontalAlignment="Left" Height="40" Margin="0" VerticalAlignment="Top" Width="40" Source="media/cat.png"/>
    </Canvas>
</Window>

代码bahind ......

    private void Canvas_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Down)
        {
            Canvas.SetTop(DogeIcon, Canvas.GetTop(DogeIcon) + 10);
        }
        else if (e.Key == Key.Up)
        {
            Canvas.SetTop(DogeIcon, Canvas.GetTop(DogeIcon) - 10);
        }
        else if (e.Key == Key.Left)
        {
            Canvas.SetLeft(DogeIcon, Canvas.GetLeft(DogeIcon) - 10);
        }
        else if (e.Key == Key.Right)
        {
            Canvas.SetLeft(DogeIcon, Canvas.GetLeft(DogeIcon) + 10);
        }
    }