在按键上移动画布

时间:2012-06-11 23:16:48

标签: wpf

当我按 - >时,我想向右移动画布。 我设置了事件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>

1 个答案:

答案 0 :(得分: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;
        }
    }