问题
Hey; I have the following visual hyerarchy in a usercontrol:
Grid -> Canvas -> MyContentControl
MyContentControl is a class derived from ContentControl that has an adorner on top that is a rectangle, this is to make it easier to click on certain objects (increase hit testing area). The adorner is present at all times, but with transparent background.
I would like to see the PreviewMouseDown events raised when I click on a MyContentControl from the usercontrol's codebehind, but the event does not seem to be raised there, only at the adorner level.
The event is handled at the adorner level, but e.IsHandled is not set to true, so it should continue bubbling or tunneling. From what I read, PreviewMouseDown is tunneling, and IIRC, it should have been raised at the usercontrol first.
Am I missing something?
Thank you.
回答1:
Given the structure that you described the actual visual tree will look something like this:
Window
-> Grid
-> Canvas
-> MyContentControl
-> AdornerLayer
-> MyContentControlAdorner
As you see, your adorner (MyContentControlAdorner
) is located in the different branch of the tree than your custom control. This is because adorners are placed inside a special element called AdornerLayer
. Such AdornerLayer
is usually located directly inside the top level element (such as Window
or Page
).
So, considering all of that, it should be clear that if an event is raised in the adorner it will tunnel by the following path: Window -> AronerLayer -> MyContentControlAdorner
.
That being said, you cannot handle a mouse event on two elements that are located in different subtrees (even though they are placed one on top of another).
来源:https://stackoverflow.com/questions/5734992/not-able-to-handle-previewmousedown