Click here to Skip to main content
15,913,313 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a code for drawing line on a canvas in wpf. The line is drawn using a mouse event. When the line is drawn it is also added to a list of Lines. I want to redraw those lines each time the canvas invalidate like we do in Paint event of winform Panel.

private void Panel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    line = true;
    Point pointToWindow = Mouse.GetPosition(this);
    Point pointToScreen = PointToScreen(pointToWindow);
    DsP1 = new Point(pointToWindow.X, pointToWindow.Y - 150);
    if (e.ButtonState == MouseButtonState.Released)
    {
        line = false;
        ln = new System.Windows.Shapes.Line();
        ln.X1 = DsP1.X;
        ln.Y1 = DsP1.Y;
        ln.X2 = e.GetPosition(Panel).X;
        ln.Y2 = e.GetPosition(Panel).Y;
        ln.Stroke = pen;
        Panel.Children.Add(ln);
        Lines.Add(ln);
    }
}

private void Panel_MouseMove(object sender, MouseEventArgs e)
{

    if (line == true && e.LeftButton==MouseButtonState.Pressed)
    {
        Panel.Children.Remove(ln);
        ln = new System.Windows.Shapes.Line();
        ln.X1 = DsP1.X;
        ln.Y1 = DsP1.Y;
        ln.X2 = e.GetPosition(Panel).X;
        ln.Y2 = e.GetPosition(Panel).Y;
        ln.Stroke = pen;
        Panel.Children.Add(ln);
    }

}


What I have tried:

I have tried overriding render with..
protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);
            foreach(Line l in Lines){
Panel.Childeren.add(l);
}
           
        }


it doesn't work... any idea
Posted
Updated 22-Mar-18 2:12am

1 solution

I am not sure I understand why you are making your life so difficult. If you bind to a viewmodel collection property, and the items in the collection support INotifyPropertyChanged, then any updates will be reflected on the canvas. Obviously there are certain performance issues always associated with Binding in WPF
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900