简体   繁体   English

如何在鼠标光标处将边距设置到位置元素

[英]How to set margin to position element at the mouse cursor

I cannot seem to figure out how to set the margins correspond to where the mouse cursor is at. 我似乎无法弄清楚如何设置与鼠标光标所处位置相对应的边距。

Sample code: 样例代码:

protected override void OnMouseMove(MouseEventArgs e)
{
  base.OnMouseMove(e);

  Connector connector = this.Template.FindName("PART_Connector", this) as Connector;
  double marginLeft = e.GetPosition(this).X - (connector.Width / 2);
  double marginTop = e.GetPosition(this).Y - (connector.Height / 2);

  connector.Margin = new Thickness(marginLeft, marginTop, 0, 0);
}

The connector positioned using margin is always off from where it is supposed to be. 使用边距定位的连接器始终偏离其应有的位置。

Any good advice? 有什么好的建议吗?


If I set the margin like this, it will work but the connector is diminished to a single point. 如果我这样设置边距,它将起作用,但是连接器会减小到单个点。 I want the connector to be 12x12 我希望连接器为12x12

marginLeft = e.GetPosition(this).X;
marginTop = e.GetPosition(this).Y;
marginRight = this.DesiredSize.Width - e.GetPosition(this).X;
marginBottom = this.DesiredSize.Height - e.GetPosition(this).Y;

connector.Margin = new Thickness(marginLeft, marginTop, marginRight, marginBottom);

When I rescale the margins to provide the space for the connectors, the connectors just disappear: 当我重新调整边距以为连接器提供空间时,连接器便消失了:

marginLeft = e.GetPosition(this).X - (connector.Width / 2);
marginTop = e.GetPosition(this).Y - (connector.Height / 2);
marginRight = this.DesiredSize.Width - e.GetPosition(this).X + (connector.Width / 2);
marginBottom = this.DesiredSize.Height - e.GetPosition(this).Y + (connector.Height / 2);

Appreciate any help here. 在这里感谢任何帮助。

OK, I got it fixed. 好的,我已经解决了。 For anyone interested in the solution, the thing to note is you NEED to provide all 4 sides of the margin. 对于对解决方案感兴趣的任何人,需要注意的是您需要提供页边空白的所有四个方面。

If you only provide left and top, the connector will sort of shift towards the right-bottom portion of the Grid. 如果仅提供左侧和顶部,则连接器将向网格的右下方移动。

Also the fix to accommodate space for the connectors is outlined below: 下面概述了用于容纳连接器空间的修复程序:

marginLeft = e.GetPosition(this).X - (connector.Width / 2);
marginTop = e.GetPosition(this).Y - (connector.Height / 2);
marginRight = this.DesiredSize.Width - e.GetPosition(this).X - (connector.Width / 2);
marginBottom = this.DesiredSize.Height - e.GetPosition(this).Y - (connector.Height / 2);

Note marginRight and marginTop need to subtract (And not add) half the size of the connector. 注意marginRight和marginTop需要减去(而不是添加)连接器大小的一半。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM