简体   繁体   中英

WPF MouseDown Event

I have a visual tree that looks like this:

A Border , containing a ScrollViewer , which contains a TexBlock .

The ScrollViewer takes up 100% of the space of the Border , and the TextBlock may or may not take up 100% of the space of the ScrollViewer depending on how the user configures it.

I want to capture a MouseDown event for when a user clicks anywhere in the Border . When I register a MouseDown event for either the Border , or the ScrollViewer , the callback does not get invoked. When I register a MouseDown event to the TextBlock , the callback does get invoked, but of course only in the clickable area of the TextBlock and not the full area of the Border .

One idea that I have is to create some sort of top level element that will go over the whole control, set it's visibility to hidden, then get the MouseDown from that.

Any suggestions? If something is not clear about this question let me know and I will fix it.

Showing Example code per request

// Need to know when a user clicks on anything inside of the border, but the 
// because there are items above it, the mouse event doesn't get invoked.
Border border = new Border();
ScrollViewer viewer = new ScrollViewer();
TextBlock textBlock = new TextBlock();

border.Content = viewer;
viewer.Child = textBlock;

You can register PreviewMouseDown event on the Border . It will also fire if a containing element is clicked.

private void Border_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
  var clickedElement = e.OriginalSource;
}

One more approach (although not that clean IMO) but it could be a useful if you require some custom behavior... maybe :)

We create custom scroll viewer and then use it instead of the standard one, our custom control will just propagate it's mouse down event to it's parent ( this example is oversimplified so it's not suitable for use in production in the current state ).

public class CustomScrollViewer : ScrollViewer
{
    protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        ((e.Source as FrameworkElement).Parent as UIElement).RaiseEvent(e);
    }
}

Some info for people like me that weren't familiar with the PreviewMouseDown approach - it's using Routing strategy called Tunneling (from top to bottom) which is the opposite of Bubbling (from bottom to top)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM