WPF FrameworkElement没有收到鼠标输入 [英] WPF FrameworkElement not receiving Mouse input
问题描述
试图使OnMouse事件出现在子FrameworkElement
中.父元素是Panel
(并且Background
属性不是Null).
Trying to get OnMouse events appearing in a child FrameworkElement
. The parent element is a Panel
(and the Background
property is not Null).
class MyFrameworkElement : FrameworkElement
{
protected override void OnMouseDown(MouseButtonEventArgs e)
{
// Trying to get here!
base.OnMouseDown(e);
}
}
public class MyPanel : Panel
{
protected override void OnMouseDown(MouseButtonEventArgs e)
{
// This is OK
base.OnMouseDown(e);
}
}
OnMouse永远不会被调用,事件始终是未处理的,Snoop告诉我,路由事件似乎只会到达Panel
元素.
OnMouse never gets called, event is always unhandled and Snoop tells me that the routed event only ever seems to get as far as the Panel
element.
<Window
x:Class="WpfApplication5.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:WpfApplication5"
Title="Window1" Height="300" Width="300">
<Border x:Name="myBorder" Background="Red">
<l:MyPanel x:Name="myPanel" Background="Transparent">
<l:MyFrameworkElement x:Name="myFE"/>
</l:MyPanel>
</Border>
</Window>
医生说FrameworkElement
处理输入,但是在这种情况下为什么不处理?
Docs say that FrameworkElement
handles Input, but why not in this scenario?
推荐答案
OnMouseDown
仅在您的元素响应点击测试时才会被调用.请参见在可视层中进行击打测试.默认实现将对 OnRender
.创建具有Transparent
背景的Panel
是可行的,因为Panel
在其整个区域上绘制一个矩形,并且该矩形将捕获命中测试.您可以通过覆盖OnRender
绘制透明矩形来获得相同的效果:
OnMouseDown
will only be called if your element responds to Hit Testing. See Hit Testing in the Visual Layer. The default implementation will do hit testing against the graphics drawn in OnRender
. Creating a Panel
with a Transparent
background works because Panel
draws a rectangle over its entire area, and that rectangle will catch the hit test. You can get the same effect by overriding OnRender
to draw a transparent rectangle:
protected override void OnRender(DrawingContext drawingContext)
{
drawingContext.DrawRectangle(Brushes.Transparent, null,
new Rect(0, 0, RenderSize.Width, RenderSize.Height));
}
您还可以覆盖 HitTestCore
,以便将所有点击都计为匹配:
You could also override HitTestCore
so that all clicks are counted as hits:
protected override HitTestResult HitTestCore(PointHitTestParameters hitTestParameters)
{
return new PointHitTestResult(this, hitTestParameters.HitPoint);
}
这篇关于WPF FrameworkElement没有收到鼠标输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!