我有一段代码可以做到这一点:
“在 WPF 中使用 Rect 类创建两个矩形,并将它们放置在标签的左边框和下边框上,以指示鼠标指针是否放置在其中任何一个中,以便调整标签的大小如果用户在这些区域中单击并拖动“
代码如下所示:
//the event handler
private void thelabel_MouseMove_1(object sender, MouseEventArgs e)
{
//if the mouse button is not pressed
if (Mouse.LeftButton == MouseButtonState.Released)
{
//locate the current mouse location
Point currentLocation = e.MouseDevice.GetPosition(this);
//the label's position
Point labelposition = thelabel.TransformToAncestor(thegrid).Transform(new Point(0, 0));
//create two Rects with 3 pixels as width and just as long as each one's corresponding border, and position them on each bottom and left borders of the label
var bottomHandle = new Rect(labelposition.X - thelabel.Width, labelposition.Y + thelabel.Height, thelabel.Width, 3);
var leftHandle = new Rect(labelposition.X - thelabel.Width, labelposition.Y, 3, thelabel.Height);
Point relativeLocation = this.TranslatePoint(currentLocation, this);
//if the left handle contains the mouse location i.e the mouse is on the left handle
if (leftHandle.Contains(relativeLocation))
{
this.Cursor = Cursors.SizeWE;
}
//if the bottom handle contains the mouse location
else if (bottomHandle.Contains(relativeLocation))
{
this.Cursor = Cursors.SizeNS;
}
else
{
//but this doesn't work when the mouse leaves the label and the two rects !
this.Cursor = Cursors.Arrow;
}
}
最后一行代码
else
{
this.Cursor = Cursors.Arrow;
}
不起作用,因为当鼠标不在标签上时,它OnMouseMove
不再被调用并且光标不会变回箭头。
我已经尝试将 an 添加OnMouseMove
到 theGrid
以及Canvas
包含标签和它的Rect
s 中,以便将光标更改回箭头。但这会影响确定鼠标是否位于任何一个Rect
s 上。
所以
问题是“我如何确定鼠标是否离开两个矩形,无论是从标签的 OnMouseMove 事件之外还是通过任何其他方式”。