Reputation: 906
XAML
<Canvas Name="canvas" MouseDown="canvas_MouseDown" MouseUp="canvas_MouseUp" Background="White" MouseMove="canvas_MouseMove" />
C#
Line AnimationLine;
Point P1;
private void canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
P1 = e.GetPosition(canvas);
AnimationLine = new Line() { Stroke = new SolidColorBrush { Color = Colors.Blue },StrokeThickness = 3};
AnimationLine.X1 = P1.X;
AnimationLine.Y1 = P1.Y;
canvas.Children.Add(AnimationLine);
}
private void canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
var P2 = e.GetPosition(canvas);
canvas.Children.Remove(AnimationLine);
//AnimationLine = new Line();
canvas.Children.Add
(new Line()
{
X1 = P1.X,
Y1 = P1.Y,
X2 = P2.X,
Y2 = P2.Y,
StrokeThickness = 3,
Stroke = new SolidColorBrush { Color = Colors.Blue }
});
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
if(e.LeftButton == MouseButtonState.Pressed)
{
var P2 = e.GetPosition(canvas);
AnimationLine.X2 = P2.X;
AnimationLine.Y2 = P2.Y;
}
}
i am trying to draw a line first point assigned on mouse down, second point assigned on mouse up and thats when the line gets drawn, but when dragging i want to show the Animation line, animation line which is like a real time guide line.
in order to get it i want to draw a line just like in microsoft paint.
i just wrote the above and it works great, but is this really the way to do it? any built in functionalities that could help?
Upvotes: 1
Views: 2979
Reputation: 128106
Your code could be simplified like shown below. In particular you should add handlers for the MouseLeftButtonDown
and MouseLeftButtonUp
events instead of the more general MouseDown
and MouseUp
events. Note also that you would typically capture the mouse, and that the only purpose for having a mouse up handler is to release the mouse capture.
XAML:
<Canvas Background="Transparent"
MouseLeftButtonDown="Canvas_MouseLeftButtonDown"
MouseLeftButtonUp="Canvas_MouseLeftButtonUp"
MouseMove="Canvas_MouseMove"/>
Code behind:
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var canvas = (Canvas)sender;
if (canvas.CaptureMouse())
{
var startPoint = e.GetPosition(canvas);
var line = new Line
{
Stroke = Brushes.Blue,
StrokeThickness = 3,
X1 = startPoint.X,
Y1 = startPoint.Y,
X2 = startPoint.X,
Y2 = startPoint.Y,
};
canvas.Children.Add(line);
}
}
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
var canvas = (Canvas)sender;
if (canvas.IsMouseCaptured && e.LeftButton == MouseButtonState.Pressed)
{
var line = canvas.Children.OfType<Line>().LastOrDefault();
if (line != null)
{
var endPoint = e.GetPosition(canvas);
line.X2 = endPoint.X;
line.Y2 = endPoint.Y;
}
}
}
private void Canvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
((Canvas)sender).ReleaseMouseCapture();
}
Upvotes: 3