0
<UserControl x:Class="MyGameSilverlight.MainPage"
    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"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" KeyDown="OnKeyDown">

    <Grid x:Name="LayoutRoot" Background="White">

            <Canvas x:Name="c1" Background="Green" Margin="0,0,130,80" RenderTransformOrigin="0.463,0.5">
                <Rectangle x:Name="obj" Height="60" Width="80" Canvas.Left="45" Canvas.Top="45" Fill="Aqua" />
            </Canvas>


    </Grid>
</UserControl>

[代码背后]

private void OnKeyDown(object sender, KeyEventArgs e)
        {
            switch (e.Key)
            {
                case Key.Right:
                    Canvas.SetLeft(obj, Canvas.GetLeft(obj) + 20);
                    break;

                case Key.Left:
                    Canvas.SetLeft(obj, Canvas.GetLeft(obj) - 20);
                    break;
                // more here
            }
        }

我在画布中有简单矩形的代码。现在我想在按键上移动这个矩形。例如,当我按下右箭头键时,矩形应该从其初始位置向右移动 20px。

代码背后的代码是什么?

4

1 回答 1

1

您可以通过静态方法Canvas.GetLeftCanvas.GetTopCanvas.SetLeftCanvas.SetTopCanvas.Left在代码中获取和设置附加属性:Canvas.Top

double left = Canvas.GetLeft(obj) + 20;
double top = Canvas.GetTop(obj) + 20;
Canvas.SetLeft(obj, left);
Canvas.SetTop(obj, top);

似乎问题是关于如何接收或处理键盘输入。您必须附加(例如)一个 KeyDown 处理程序,但您必须知道 UIElement 需要具有键盘焦点才能接收键事件。由于 Rectangle 和 Canvas 都不是可聚焦的(请参阅Focus Overview),您可以将处理程序附加到您的 MainPage:

<UserControl ... KeyDown="OnKeyDown">
    <Canvas>
        <Rectangle Name="obj" .../>
    </Canvas>
</UserControl>

在处理程序中,您将像这样处理各个键:

private void OnKeyDown(object sender, KeyEventArgs e)
{
    switch (e.Key)
    {
        case Key.Right:
            Canvas.SetLeft(obj, Canvas.GetLeft(obj) + 20);
            break;
        // more here
    }
}
于 2013-03-17T20:31:45.413 回答