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