tags:

views:

112

answers:

4

My first WPF application, but it is not working. Help please!

xaml:
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="308" Width="527">
    <Grid Name="canvas">
        <Canvas></Canvas>
    </Grid>
</Window>

Code behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            Line line = new Line();
            line.X1 = 0;
            line.Y1 = 100;
            line.X2 = 0;
            line.Y2 = 100;
            line.Stroke = Brushes.Red;
            line.StrokeThickness = 1; // Note1
            canvas.Children.Insert(0, line);
        }
    }
}
+4  A: 

What I see is your first X,Y coordinate and second are the same. So the line being drawn is over the same point.

line.X1 = 0;
line.Y1 = 100;
line.X2 = 0;
line.Y2 = 100;

// Change too this and that will will draw straight over 100 pixels.
line.X1 = 0;
line.Y1 = 100;
line.X2 = 100;
line.Y2 = 100;
David Basarab
+3  A: 

It does work.

But you are creating a single point not a line, and adding it to the grid, not the canvas. In fact, I don't think you'll even see a point with the start and end points being the same.

Change X2 to 300 and you'll see a red line.

SergioL

SergioL
+5  A: 

Your X1/Y1 values are the same as the X2/Y2 values. If you change line.X2 = 0; to line.X2 = 50;, you'll see your line.

If your line isn't going to be dynamic though, it's generally best practice to do most visual stuff in XAML directly like so:

    <Grid Name="canvas">
    <Line X1="0" Y1="100" X2="50" Y2="100" StrokeThickness="1" Stroke="Red" />
</Grid>

Hope this helps, Andy

Andy
A: 

Thanks guys! You all answered my question, but I can't log on and can't mark any answer as solution. Sorry.

Mike