2

I have a WPF project where i had to plot some lines in the project. But when i resize the window, the lines wouldn't resize because i using the canvas coordinate to plot the line. Anyone show me how to make the line resize vary to the window size?

my code for the line:

public static void drawGridLines(MainWindow main)
    {
            double axisX = 10;
            Line lastLine = new Line();
            lastLine.X2 = axisX;
            lastLine.Y2 = 15;
            double y = 0;
            double x = 0;
            bool first = true;
            int[] point = new int[10] { 1, 3, 8, 9, 9, 0, 7, 5, 4, 1 };

        for (int i = 0; i < point.Length; i++) // iterate over your gridview rows 
            {
                Line newline = new Line();

                newline.X1 = lastLine.X2;
                newline.Y1 = lastLine.Y2;

                newline.X2 = axisX + (Point[i] * 5); // calculate X position of the current cell 
                newline.Y2 = lastLine.Y2 + 10; // calculate Y position of the current cell 
                x = newline.X2;
                y = newline.Y2;

                if (!first)
                {
                    // first minimum cell should't be drawn, it is just the start point for next line                  
                    drawLine(main, newline);
                }
                else
                {
                    first = false;
                }

                lastLine = newline;
            }


public static void drawLine(MainWindow main, Line line)
    {
        line.HorizontalAlignment = HorizontalAlignment.Left;
        line.VerticalAlignment = VerticalAlignment.Center;
        line.Stroke = System.Windows.Media.Brushes.SteelBlue;
        line.StrokeThickness = 1.5;
        main.myLineCanvas.Children.Add(line);

    }
Nerdynosaur
  • 1,798
  • 9
  • 32
  • 61

3 Answers3

2

Place your Canvas in a Viewbox:

<Viewbox>
    <Canvas x:Name="myLineCanvas" />
</Viewbox>

You can change its behavior with Stretch and StretchDirection.

enter image description here

user7116
  • 63,008
  • 17
  • 141
  • 172
  • your solution doesn't work neatly with my wpf project. For my situation, i need to add the lines into a table with cells. After resizing, the line doesn't fit very well in the canvas. Btw, thanks for your info. – Nerdynosaur Nov 19 '12 at 02:50
1

You should try using a ViewBox and see if it works well in your case, is as simple as surrounding your canvas with the ViewBox.

<Window ...
    ...>

    <ViewBox>
        <Canvas .....>
        </Canvas>
    </ViewBox>
</Window>
Salvador Sarpi
  • 981
  • 1
  • 8
  • 19
0

Window has a SizeChanged event. In your handler you can grab the new size of your window and set the endpoints of your lines accordingly.

Josh C.
  • 4,303
  • 5
  • 30
  • 51