【问题标题】:Change the location of an object programmatically以编程方式更改对象的位置
【发布时间】:2012-01-12 06:56:43
【问题描述】:
我试过下面的代码:
this.balancePanel.Location.X = this.optionsPanel.Location.X;
在程序运行时更改我在设计模式下创建的面板的位置,但它返回错误:
不能修改'System.Windows.Forms.Control.Location'的返回值,因为它不是一个变量。
那我该怎么做呢?
【问题讨论】:
标签:
c#
winforms
controls
runtime
【解决方案1】:
Location 属性的类型为 Point,它是一个结构体。
与其尝试修改现有的Point,不如尝试分配一个新的Point 对象:
this.balancePanel.Location = new Point(
this.optionsPanel.Location.X,
this.balancePanel.Location.Y
);
【解决方案2】:
位置是一个结构。如果没有任何便利成员,您需要重新分配整个位置:
this.balancePanel.Location = new Point(
this.optionsPanel.Location.X,
this.balancePanel.Location.Y);
大多数结构体也是不可变的,但在罕见(且令人困惑)可变的情况下,您还可以复制、编辑、复制;
var loc = this.balancePanel.Location;
loc.X = this.optionsPanel.Location.X;
this.balancePanel.Location = loc;
虽然我不推荐上述方法,因为理想情况下结构应该是不可变的。
【解决方案3】:
使用任一:
balancePanel.Left = optionsPanel.Location.X;
或
balancePanel.Location = new Point(optionsPanel.Location.X, balancePanel.Location.Y);
见documentation of Location:
因为 Point 类是值类型(Visual Basic 中的结构,
Visual C#中的struct),它是按值返回的,这意味着访问
属性返回控件左上角的副本。所以,
调整由此返回的点的 X 或 Y 属性
属性不会影响 Left、Right、Top 或 Bottom 属性
控件的值。要调整这些属性,请设置每个属性
单独设置值,或使用新点设置 Location 属性。
【解决方案4】:
如果 balancePanel 不能正常工作,你可以使用这个:
this.Location = new Point(127, 283);
或
anotherObject.Location = new Point(127, 283);
【解决方案5】:
您需要将整个点传递给位置
var point = new Point(50, 100);
this.balancePanel.Location = point;
【解决方案6】:
当父面板的 lock 属性设置为 true 时,我们无法更改 location 属性,此时 location 属性将像只读一样。