0

我有一段代码可以做到这一点:
“在 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包含标签和它的Rects 中,以便将光标更改回箭头。但这会影响确定鼠标是否位于任何一个Rects 上。

所以
问题是“我如何确定鼠标是否离开两个矩形,无论是从标签的 OnMouseMove 事件之外还是通过任何其他方式”。

4

1 回答 1

0

当您说“包含...矩形的画布”时,我猜您的意思是Rectangle

为了实现拖动,您应该将事件处理程序附加到这些矩形(而不是标签)以用于以下鼠标事件:

  • MouseEnter - 设置拖动光标
  • MouseLeave - 重置光标
  • MouseDown 或 MouseLeftButtonDown - 通过捕获鼠标开始拖动,
  • MouseUp 或 MouseLeftButtonUp - 通过释放鼠标捕获结束拖动
  • MouseMove - 实际拖动
于 2013-01-07T10:00:31.100 回答