当鼠标离开WPF中动态生成的Rect时,如何更改鼠标光标?
我有一段代码可以做到这一点:当鼠标离开WPF中动态生成的Rect时,如何更改鼠标光标?,wpf,mouseleave,rect,mouse-cursor,Wpf,Mouseleave,Rect,Mouse Cursor,我有一段代码可以做到这一点: 使用WPF中的Rect类创建两个矩形,并将它们放置在标签的左边框和下边框上,以指示鼠标指针是否放置在其中一个边框内,以便在用户单击并拖动这些区域时调整标签的大小 代码如下所示: //the event handler private void thelabel_MouseMove_1(object sender, MouseEventArgs e) { //if the mouse button is not pressed
使用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
不再被称为,并且光标不会变回箭头
我尝试在网格
以及包含标签的画布
中添加了OnMouseMove
,以将光标更改回箭头。但这会影响确定鼠标是否位于Rect
s上
所以问题是“我如何确定鼠标是否离开这两个矩形,或者是从标签的OnMouseMove事件外部离开,或者是通过任何其他方式离开”。当你说“画布包含…矩形”时,我想你指的是s 为了实现拖动,您应该为以下鼠标事件将事件处理程序附加到这些矩形(而不是标签):
- 鼠标指针-设置拖动光标
- 鼠标移动-重置光标
- MouseDown或MouseLeftButtonDown-开始拖动
- MouseUp或MouseLeftButtonUp-通过拖动结束
- 鼠标移动-实际拖动
MouseLeave EventHandler
中的this.Cursor=Cursors.Arrow
应该可以。不可以:/因为这些矩形的一个或两个像素在标签的边界之外……您使用的是矩形吗?这些矩形是画布的子对象吗?如果是,使用克莱门斯溶液,如果不是,我的应该有效。不管有多少矩形在标签外,mousemove事件都不会在标签外触发。实际上我使用的是Rects
。我假设有一点不同(矩形和矩形)。但是,是的,我将它们添加到画布中。谢谢你的建议。我会两个都试试,让你知道哪一个有效;)我想他们是不同的Rect
使用System.Windows
命名空间,但Rectangle
使用System.Drawing
。还有一些方法可以创建Rect的新实例,而不是矩形。参考资料:我将在这里尝试您的解决方案和反馈。谢谢你的建议;)我的意思是System.Windows.Shapes.Rectangle
,一个WPF形状。画布不能“包含”System.Windows.Rect
子对象。但是,它们可能在画布.OnRender
中绘制。我很好奇你会如何在画布上“添加”矩形。