Firstly, I will not manipulate the coordinates, since they are intended primarily to determine the shape of the line. Secondly, I would not use Canvas, but Render Transformation instead, since it potentially runs on the GPU instead of the CPU, which makes the animation smoother.
So, I would do something like this:
XAML:
<Grid x:Name="LayoutRoot"> <Line x:Name="crosshair" HorizontalAlignment="Left" VerticalAlignment="Top" Stroke="Red" X1="0" X2="0" Y1="10" Y2="0" /> <Button Width="50" Height="50" HorizontalAlignment="Right" Click="MoveRight" Content=">" /> </Grid>
Code for:
public partial class MainWindow : Window { private int moveRightDist = 0; public MainWindow() { InitializeComponent(); } private void MoveRight(object sender, RoutedEventArgs e) { this.moveRightDist++; crosshair.RenderTransform = new TranslateTransform(this.moveRightDist, 0); } } <Grid x:Name="LayoutRoot"> <Line x:Name="crosshair" HorizontalAlignment="Left" VerticalAlignment="Top" Stroke="Red" X1="0" X2="0" Y1="10" Y2="0" /> <Button Width="50" Height="50" HorizontalAlignment="Right" Click="MoveRight" Content=">" /> </Grid>
Important! If you define an Affine transformation matrix in XAML and animate it, at some point WPF will replace an instance of that matrix, and if you reference this matrix in your code, you may not be able to manipulate the object.
Side note. I would prefer to create all the user interface elements in XAML (Blend is a great tool for this), and then will use the links to them from the code.
Vitalij
source share