Draw line and move it programmatically

前端 未结 2 844
情歌与酒
情歌与酒 2021-02-09 13:00

I want to draw a line on a WPF Grid.

private void InitializeTestline()
{
    testline = new Line();
    grid.Children.Add(testline);
    testline.X1 = 0;
    tes         


        
2条回答
  •  走了就别回头了
    2021-02-09 13:37

    Firstly, I would not manipulate coordinates as their are primarily for defining shape of the line. Secondly, I wouldn't use Canvas, but Render Transformation instead, as it potentially runs on GPU instead of CPU which makes animation smoother.

    So I would do something like this:

    XAML:

    
    
        
    
        

    Code Behind:

       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);
            }
        }
    
    
    
        
    
        

    Important! If you define Affine transformation matrix in XAML and animate it, at some point WPF will substitute the instance of that matrix and if you are refering to that matrix in your code you might not be able to manipulate an object.

    Side Note: I would rather create all UI elements in XAML (Blend is a great tool for that) and then would use refer to them from code behind.

提交回复
热议问题