C#WPF-矩形MouseEnter和MouseLeave事件无法正常运行

时间:2018-10-20 08:54:29

标签: c# wpf events

我向WPF画布添加一堆矩形,如下所示:

Rectangle rectangle = new Rectangle
{
    Width = tuple.Width,
    Height = tuple.Height,
    Stroke = Brushes.Black,
    StrokeThickness = 1
};

rectangle.MouseEnter += (s, e) => rectangle.Stroke = Brushes.Gray;
rectangle.MouseLeave += (s, e) => rectangle.Stroke = Brushes.Black;

Canvas.SetLeft(rectangle, tuple.X);
Canvas.SetTop(rectangle, tuple.Y);
canvas.Children.Add(rectangle);

我期望什么:

  • 鼠标正在输入的矩形的边框颜色变为灰色,只要鼠标在该矩形区域内,它就会保持灰色

实际发生的事情:

  • 仅当鼠标直接位于边框上时,边框颜色才会变为灰色;而如果鼠标在其他任何地方(即使在矩形内),边框颜色仍会保持黑色。

那为什么呢?如何实现预期的行为?

1 个答案:

答案 0 :(得分:0)

如果给矩形填充,一切都会按预期进行:

Rectangle rectangle = new Rectangle
{
    Width = tuple.Width,
    Height = tuple.Height,
    Stroke = Brushes.DarkGray,
    StrokeThickness = 1,
    Fill = Brushes.Transparent
};