For simplifying the problem, I created a simple code snippet with the same problem:
<Window x:Class="WPFTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Canvas x:Name="drawingCanvas"
MouseLeftButtonDown="drawingCanvas_MouseLeftButtonDown"
Background="White"
MouseMove="drawingCanvas_MouseMove"
MouseLeftButtonUp="drawingCanvas_MouseLeftButtonUp" />
</Grid>
</Window>
When I try to use the MouseLeftButtonUp
event, it does not work most of the time. Also by using PreviewMouseLeftButtonUp
. Can someone tell me why it is like this and offer any suggestions to solve this problem?
namespace WPFTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
drawMode = false;
startPoint = new Point();
endPoint = new Point();
}
private bool drawMode;
private bool alreadyForm;
private Point startPoint;
private Point endPoint;
private void drawingCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
drawMode = true;
alreadyForm = false;
startPoint = e.GetPosition(drawingCanvas);
}
private void drawingCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
drawMode = false;
alreadyForm = false;
Debug.WriteLine("the event was detected.");
}
private void drawingCanvas_MouseMove(object sender, MouseEventArgs e)
{
if (drawMode)
{
if (alreadyForm)
drawingCanvas.Children.RemoveAt(drawingCanvas.Children.Count-1);
endPoint = e.GetPosition(drawingCanvas);
Line newLine = new Line();
newLine.X1 = startPoint.X;
newLine.Y1 = startPoint.Y;
newLine.X2 = endPoint.X;
newLine.Y2 = endPoint.Y;
newLine.Stroke = Brushes.Black;
newLine.StrokeThickness = 4;
drawingCanvas.Children.Add(newLine);
alreadyForm = true;
}
}
}
}
I tried to solve the problem with the PreviewMouseLeftButtonUp
event but it was the same.
I tried to use e.Handled = true;
but it's also the same