WPF MouseDown事件

时间:2015-11-04 16:04:18

标签: c# wpf mouseevent

我有一个看起来像这样的可视树:

Border,其中包含ScrollViewer,其中包含TexBlock

ScrollViewer占据Border空间的100%,而TextBlock可能会占用ScrollViewer取决于MouseDown空间的100%关于用户如何配置它。

我希望在用户点击Border中的任意位置时捕获MouseDown个事件。当我为BorderScrollViewer注册MouseDown事件时,不会调用回调。当我向TextBlock注册TextBlock事件时,会调用回调,但当然只会在Border的可点击区域而不是MouseDown的完整区域}。

我的一个想法是创建某种顶层元素,它将覆盖整个控件,将其可见性设置为隐藏,然后从中获取// 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;

有什么建议吗?如果对这个问题不清楚,请告诉我,我会解决它。

显示每个请求的示例代码

/* Global stuff */
html, body  { box-sizing: border-box; height: 100%; width: 100%;
              margin: 0; padding: 0; border: 0 }
*, *:before,
*:after     { box-sizing: inherit }

/* Solution */
#w1         { display: flex; 
              flex-flow: column wrap;    /* vertical arrangement */
              align-items: flex-end;     /* forces 2&3 to lower right */
              with: 100%; height: 100% } /* full screen */

#i1         { width: 100%; height: 50% } /* full width, half height of #w1 */
#i2,#i3     { width:  50%; height: 25% } /* half width, half height of #w1 */

#w2         { display: flex; flex-direction: column;/* stay unchanged */
              position: absolute; top: 50%;         /* nasty, but works */
              width:  50%; height: 50% }            /* stay unchanged */

#i4,#i5     { width: 100%; height: 50%  }           /* stay unchanged */

#i1::before { content: 'mobile '}

@media all and (min-width: 720px) {

    #i1::before { content: 'desktop '}

    /* become equal in size */
    #i1,#i2,#i3 { width:  50%; height: 50% }    /* half width, half height of #w1 */

    #w1         { flex-flow: row wrap;          /* horizontal arrangement */
                  justify: content: flex-start }/* forces 1&2&3 to upper left */   
    #w2         { right: 0 }                    /* reposition, nasty, but works */
}      

/* Demo */
#w1 *, #w2 *    { text-align: center; font-size: 40px; font-weight: bold;
                  background: #f0f0f0; border: 2px solid black }

2 个答案:

答案 0 :(得分:1)

您可以在PreviewMouseDown上注册Border个活动。如果单击包含元素,它也会触发。

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

答案 1 :(得分:0)

另一种方法(虽然不是那种干净的IMO)但如果你需要一些自定义行为它可能是有用的......也许:))

我们创建自定义滚动查看器,然后使用它而不是标准滚动查看器,我们的自定义控件只会将它的鼠标按下事件传播到它的父级(此示例过于简单,因此它不适合在当前的生产中使用状态)。

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

像我这样不熟悉PreviewMouseDown方法的人的一些信息 - 它使用路由策略称为隧道(从上到下)与冒泡(从下到上)相反