【问题标题】:Top element prevet firing of MouseUp for the back element顶部元素为后部元素预触发 MouseUp
【发布时间】:2014-01-29 20:49:39
【问题描述】:

我正在 WPF 中设计一个 UserControl。有一个带有一些路径的画布。在这些路径中,我有两个椭圆(图片的顶部和底部)。当 Ellipses 的 MouseUp 事件被触发时,我正在做一些工作,但是当用户单击加/减路径时,它们没有触发!我见过thisthis。但似乎这里的冒泡和隧道效应并非如此,因为椭圆中不包含减/加路径。这是其中一个省略号的代码:

<Canvas Width="96" Height="550" MouseUp="plusPath_MouseUp" Background="Transparent">
    <Path x:Name="Path" Width="96" Height="550" Canvas.Left="0"  StrokeThickness="6" StrokeLineJoin="Round" Stroke="#FF465546" Canvas.Top="0" Stretch="Fill" Data="..."/>
    <Ellipse x:Name="zoomIn"  Width="68" Height="68" Canvas.Left="14" Canvas.Top="18.5143" />
    <Ellipse x:Name="zoomOut" Width="68" Height="68" Canvas.Left="14" Canvas.Top="468.79" />
    <Path  x:Name="minusPath" Cursor="Hand" Width="36" Height="6" Canvas.Left="30" Canvas.Top="500" Stretch="Fill" StrokeThickness="6" StrokeLineJoin="Round" Stroke="#FF87A698" Data="F1 M 33.0001,501.956L 63.0001,501.956"/>
    <Path  x:Name="plusPath" Cursor="Hand" Width="36.0001" Height="36" Canvas.Left="30" Canvas.Top="34" Stretch="Fill" StrokeThickness="6" StrokeLineJoin="Round" Stroke="#FF87A698" Data="M 34.0658,52.181L 64.0659,52.181M 49.0657,67.181L 49.0657,37.181"/>
</Canvas>

我应该处理减号/加号路径的MouseUp 事件还是有更好的方法?

编辑:我正在寻找最佳做法。

【问题讨论】:

    标签: c# wpf routedevents


    【解决方案1】:

    处理容器元素(例如 Grid、DockPanel、Canvas 等)上的 MouseUp,因为每当在子元素(椭圆或路径)上引发 MouseUp 事件时,它会冒泡到根元素(帆布)

    <Canvas MouseUp="Handler">
       <Ellipse/>
       <Path/>
    </Canvas>
    

    如果您想知道哪个元素实际引发了事件,您可以通过检查e.OriginalSource 来获取事件的原始发送者。 (椭圆或路径)。

    private void Handler(object sender, MouseButtonEventArgs e)
    {
        // Check actual sender here which can be Canvas, Ellipse or Path.
        Ellipse senderObject = e.OriginalSource as Ellipse;
        if(senderObject == null)
        {
           Path senderPath = e.OriginalSource as Path;
        }
    }
    

    【讨论】:

    • 所以我也应该为路径设置 MouseUp 事件。并检查是否必须进行 zoomIn 操作或 zoomOut。我说的对吗?
    • 否,处理容器上的 MouseUp 事件(即Canvas)。也从椭圆中删除 mouseUp。
    • 好的。找出单击了哪个椭圆的最佳方法是什么?顶部还是底部?
    • 在处理程序中你会得到MouseButtonEventArgs。检查其中的OriginalSource 属性,该属性将是您单击的椭圆。 e.OriginalSource 将为您提供椭圆或路径对象(无论哪个孩子引发事件)。
    • 我做到了,但事件根本没有触发。
    【解决方案2】:

    您可以将EllipsePath 都放入Grid 并在那里捕获MouseUp="zoomIn_MouseUp"

    <Grid Cursor="Hand" MouseUp="zoomIn_MouseUp" Canvas.Left="14" Canvas.Top="18.5143">
        <Ellipse x:Name="zoomIn"  Width="68" Height="68"/>
        <Path x:Name="plusPath" StrokeThickness="6" Width="36.0001" Height="36" StrokeLineJoin="Round" Stretch="Fill" Stroke="#FF87A698" Data="M 34.0658,52.181L 64.0659,52.181M 49.0657,67.181L 49.0657,37.181"/>
    </Grid>
    

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多