0

I'm new to MVVM and I am struggling to find a solution to my problem, which is modifying lines coordinates as children to a canvas. My project consist of controlling a robot arm with GUI, the user should enter a point and the robot moves and also this action should modify lines in canvas that represent the connected arms.

How can I bind data to a child of canvas parent? Or how can I modify children dynamically?

This the XAML part of canvas :

<Canvas x:Name="myCanvas" Cursor = "Cross"
            DataContext="{Binding myCanvas, UpdateSourceTrigger=PropertyChanged , Mode=TwoWay}"
            Grid.Column="1"
            Width="500"
            Height="500"
            Background="#FF282828">
        <Line Visibility="Visible" 
             Stroke="LightGray" 
             Opacity="0.8"
             StrokeThickness="1"
             X1="250" Y1="0"
             X2="250" Y2="500"/>
        <Line Visibility="Visible" 
             Stroke="LightGray" 
             Opacity="0.8"
             StrokeThickness="1"
             X1="0" Y1="250"
             X2="500" Y2="250"/>
        <Path Visibility="Visible" Stroke="LightGray"
              StrokeThickness="1">
            <Path.Data>
                <EllipseGeometry Center="250 250" 
                                 RadiusX="10"
                                 RadiusY="10"/>
            </Path.Data>
        </Path>

    </Canvas>

Those lines here just represent the grid of the canvas and the circle is a center of the robot.

I want to be able to rotate the two arms programmatically using the viewModel!

It worked perfectly without the MVVM method, where I could directly control everything on the canvas.

I shall use those methods to rotate the lines :

    private double oldt = 0.0f, oldt2 = 0.0f;
    public double scale;

    public void rotateL1(double t1)
    {
        scale = myCanvas.Height / 6;
        l1.X2 = l1.X1 + scale * Math.Sin(t1);
        l1.Y2 = l1.Y1 - scale * Math.Cos(t1);
        
        l2.X1 = l1.X2;
        l2.Y1 = l1.Y2;
        oldt = t1;
        rotateL2(oldt2);
    }

    public void rotateL2(double t2)
    {
        scale = myCanvas.Height / 6;
        l2.X2 = l2.X1 + scale * Math.Sin(oldt - t2);
        l2.Y2 = l2.Y1 - scale * Math.Cos(oldt - t2);
        oldt2 = t2;
    }

When ever I find solution it does implement ItemsControl and forget about the canvas part. Please help me !!

  • 1
    Use a Canvas as ItemsPanel of an ItemsControl, similar to the solution shown [here](https://stackoverflow.com/a/22325266/1136211) or [here](https://stackoverflow.com/a/40190793/1136211) or [here](https://stackoverflow.com/a/25031206/1136211). – Clemens Dec 24 '21 at 22:13

0 Answers0