Search code examples
wpfeventsraise

Raising WPF MouseLeftButtonDownEvent event programmatically


I am trying to raise a MouseLeftButtonDownEvent by bubbling it up the Visual tree with the following code.

var args = new MouseButtonEventArgs(Mouse.PrimaryDevice,0,MouseButton.Left);
args.RoutedEvent = UIElement.MouseLeftButtonDownEvent;
args.Source = this;
RaiseEvent(args);

For some reason the higher level components are not receiving this bubbled event. Am I overlooking something or is it not possible to raise this Mouse event


Solution

  • Your problem is that you are raising an event that does not bubble.

    MouseLeftButtonDownEvent is defined as RoutingStrategy.Direct, which means it is routed to only the control receiving the event.

    You want to use Mouse.MouseDownEvent event instead. UIElement and other classes internally convert this into a MouseLeftButtonDownEvent. Make sure you set e.ChangedButton to MouseButton.Left:

    RaiseEvent(new MouseButtonEventArgs(Mouse.PrimaryDevice, 0, MouseButton.Left)
    {
      RoutedEvent = Mouse.MouseDownEvent,
      Source = this,
    });