此问题与 another question 相关我也几乎没有问过。
我有一个 Canvas ,其中包含路径和文本 block 。
<Canvas>
<Path Name="pathNodeType" StrokeThickness="1">
<Path.Style>
<Style>
<Setter Property="Path.Stroke" Value="Black" />
<Setter Property="Path.Fill" Value="LightGray" />
<Style.Triggers>
<Trigger Property="Canvas.IsMouseOver" Value="True">
<Setter Property="Path.Stroke" Value="Blue" />
<Setter Property="Path.Fill" Value="LightBlue" />
</Trigger>
</Style.Triggers>
</Style>
</Path.Style>
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigureCollection>
<PathFigure IsClosed="True" StartPoint="20,40">
<PathFigure.Segments>
<PathSegmentCollection>
<ArcSegment Size="10,10" RotationAngle="45" IsLargeArc="True" SweepDirection="Clockwise" Point="50,40" />
<LineSegment Point="50,60" />
<LineSegment Point="20,60" />
</PathSegmentCollection>
</PathFigure.Segments>
</PathFigure>
</PathFigureCollection>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
<TextBlock HorizontalAlignment="Left" Margin="22,40,0,0" TextWrapping="Wrap" Text="AND" VerticalAlignment="Top" FontWeight="Bold"/>
</Canvas>
当鼠标指针位于绘制的路径上时, Canvas 的 IsMouseOver 属性会触发路径样式,正如我所期望的那样。但是,当鼠标指针位于文本 block 上方(位于绘制路径的正中间)时,路径样式不会像我预期的那样触发。
为什么不触发?文本 block 驻留在 Canvas 内,所以从技术上讲,鼠标指针不是也在 Canvas 上吗?
预先感谢您对此提供的任何帮助。
最佳答案
原因是,您将触发器的属性设置为Canvas.IsMouseOver,因此当鼠标悬停在Canvas上时它将触发。 但是当您在路径的样式中设置触发器时,这将限制在路径的区域内。
我知道 IsMouseOver 是一个属性,但我想使用 MouseEnter 作为示例。 MouseEnter 是一个路由事件,因此当鼠标悬停在 TextBlock 上时,它将作为路由事件触发,TextBlock 的 MouseEnter 事件将触发,并且可能 TextBlock 的 IsMouseOver 变为 true,而不是 Path 和 Canvas 。因为现在TextBlock的ZIndex是最高的。
所以,我们需要做的是让 TextBlock 的 IsMouseOver 在悬停时不发生变化。
我们可以设置TextBlock的IsHitTestVisible="False";
代码可以是这样的: 我已经测试过这段代码,它有效!
<Canvas Background="Transparent">
<Path Name="PathNodeType" StrokeThickness="1">
<Path.Style>
<Style TargetType="Path">
<Setter Property="Stroke" Value="Black" />
<Setter Property="Fill" Value="LightGray" />
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Stroke" Value="Blue" />
<Setter Property="Fill" Value="LightBlue" />
</Trigger>
</Style.Triggers>
</Style>
</Path.Style>
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigureCollection>
<PathFigure IsClosed="True" StartPoint="20,40">
<PathFigure.Segments>
<PathSegmentCollection>
<ArcSegment IsLargeArc="True"
Point="50,40"
RotationAngle="45"
Size="10,10"
SweepDirection="Clockwise" />
<LineSegment Point="50,60" />
<LineSegment Point="20,60" />
</PathSegmentCollection>
</PathFigure.Segments>
</PathFigure>
</PathFigureCollection>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
<TextBlock Margin="22,40,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
FontWeight="Bold"
Text="AND" IsHitTestVisible="False"
TextWrapping="Wrap" />
</Canvas>
关于wpf - IsMouseOver 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18473156/