Drawing lines in code using C# and WPF

Jesse picture Jesse · May 11, 2011 · Viewed 56.4k times · Source

I'm trying to create a digital clock display using 7 segment displays. I can draw lines in XAML by using code like this:

<Line Name="line7" Stroke="Black" StrokeThickness="4" X1="10" X2="40" Y1="70" Y2="70" Margin="101,-11,362,250" />

But when I try to do it in code(from MainWindow()), it doesn't work:

        Line line = new Line();
        Thickness thickness = new Thickness(101,-11,362,250);
        line.Margin = thickness;
        line.Visibility = System.Windows.Visibility.Visible;
        line.StrokeThickness = 4;
        line.Stroke = System.Windows.Media.Brushes.Black;
        line.X1 = 10;
        line.X2 = 40;
        line.Y1 = 70;
        line.Y2 = 70;

The idea is I can draw 7 lines, then toggle their visibility as required for different numbers. I'm sure this can be done many ways, but why can't I draw lines in code like this?

Answer

keyboardP picture keyboardP · May 11, 2011

Is that your entire drawing code? If so, you need to add the line object to your surface. If you're using a Canvas for example:

myCanvas.Children.Add(line);

This will add your line to your canvas. At the moment, you're just creating the line but not putting it anywhere.

You can find more information on drawing in WPF on this MSDN page.