2

当我按下 -> 时,我想向右移动画布。我设置了事件 KeyDown,这是事件的方法

private void Window_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key==Key.Right)
    {

    }
}

但是里面写什么if呢?Canvas.setLeft不工作

 <Canvas x:Name="totle" KeyDown="Window_KeyDown">
        <Ellipse  Name="yio" Canvas.Left="40" Canvas.Top="40" Height="30" Width="30" Fill="Beige"/>
        <Line X1="40" Canvas.Left="67" Canvas.Top="51" StrokeThickness="40" Stroke="Red" Height="10" Width="45" Fill="#FFD86464" OpacityMask="Red" />
        <Rectangle Canvas.Left="20" Canvas.Top="70" Width="70" Height="20" Fill="Beige"/>
    </Canvas>
4

1 回答 1

3

要实现这个效果,首先使用一个RenderTransform并将其命名为canvasTranform:

<Canvas x:Name="totle" KeyDown="Window_KeyDown">
    <Canvas.RenderTransform>
        <TranslateTransform x:Name="canvasTransform" />
    </Canvas.RenderTransform>
    <Ellipse  Name="yio" Canvas.Left="40" Canvas.Top="40" Height="30" Width="30" Fill="Beige"/>
    <Line X1="40" Canvas.Left="67" Canvas.Top="51" StrokeThickness="40" Stroke="Red" Height="10" Width="45" Fill="#FFD86464" OpacityMask="Red" />
    <Rectangle Canvas.Left="20" Canvas.Top="70" Width="70" Height="20" Fill="Beige"/>
</Canvas>

然后,在您的事件处理程序中,TranslateTransform按名称引用并设置X属性:

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Right)
        {
            canvasTransform.X = 100;
        }
    }

如果您的变换是加法的(当您按下右箭头时,画布会一直向右移动),X每次都添加到属性中:

    private void Window_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Right)
        {
            canvasTransform.X += 100;
        }
    }
于 2012-06-12T00:51:46.690 回答