Home > Software design >  WPF MouseLeftButtonDown makes FlowDocument unable to select text
WPF MouseLeftButtonDown makes FlowDocument unable to select text

Time:11-15

I add a function that adds text to FlowDocument when the mouse clicks. There is no Click event in FlowDocument, so I listen to FlowDocument.MouseLeftButtonDown and MouseLeftButtonUp and check whether the mouse moves between down and up. When I click the mouse left button, the text successfully adds. However, I can't select any text in the FlowDocument.

I tried PreviewMouseLeftButtonDown and PreviewMouseLeftButtonUp. The behavior is the same. Isn't there a PostMouseLeftButtonDown?

My Code:

        Point mouseDownPoint;
        private void doc_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            mouseDownPoint = Mouse.GetPosition(doc);
            e.Handled = true;
        }

        private void doc_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            var mouseUpPoint = Mouse.GetPosition(doc);
            if ((mouseUpPoint - mouseDownPoint).Length < 8) /* add text */;
        }

CodePudding user response:

The control handles the event internally.

If you register the event handler programmatically like this, your doc_MouseLeftButtonUp event handler should get invoked (note that last handledEventsToo parameter):

doc.AddHandler(ContentElement.MouseLeftButtonUpEvent, 
    (MouseButtonEventHandler)doc_MouseLeftButtonUp, true);

Note that you may also have to take care of the MouseLeftButtonUp that is raised by the control itself.

CodePudding user response:

I found the solution. Listen to FlowDocument.MouseLeftButtonDown and do not use e.Handled=true and listen to FlowDocumentScrollViewer.PreviewMouseLeftButtonUp will get text selection and add text behavior at the same time.

  • Related