C# 以编程方式更改对象的位置

C# 以编程方式更改对象的位置,c#,winforms,controls,runtime,C#,Winforms,Controls,Runtime,我尝试了以下代码: this.balancePanel.Location.X = this.optionsPanel.Location.X; 要在程序运行但返回错误时更改我在设计模式下制作的面板的位置,请执行以下操作: 无法修改“System.Windows.Forms.Control.Location”的返回值,因为它不是变量 那么我该怎么做呢?属性的Location类型为Point,它是一个结构 与其尝试修改现有的点,不如尝试分配一个新的点对象: this.balancePanel.L

我尝试了以下代码:

 this.balancePanel.Location.X = this.optionsPanel.Location.X;
要在程序运行但返回错误时更改我在设计模式下制作的面板的位置,请执行以下操作:

无法修改“System.Windows.Forms.Control.Location”的返回值,因为它不是变量


那么我该怎么做呢?

属性的
Location
类型为
Point
,它是一个结构

与其尝试修改现有的
,不如尝试分配一个新的
对象:

 this.balancePanel.Location = new Point(
     this.optionsPanel.Location.X,
     this.balancePanel.Location.Y
 );

您需要将整个点传递到位置

var point = new Point(50, 100);
this.balancePanel.Location = point;

位置是一个结构。如果没有任何便利会员,则需要重新分配整个位置:

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;
尽管我不建议使用上述方法,因为结构在理想情况下应该是不可变的。

使用以下任一方法:

balancePanel.Left = optionsPanel.Location.X;

见:

因为Point类是一种值类型(VisualBasic中的结构, 在Visual C#中,它是通过值返回的,这意味着访问 属性返回控件左上角点的副本。所以 调整由此返回的点的X或Y属性 属性不会影响“左”、“右”、“上”或“下”属性 控件的值。要调整这些属性,请设置每个属性 值,或使用新点设置位置特性


如果balancePanel无法正常工作,您可以使用:

this.Location = new Point(127, 283);


当父面板已将locked属性设置为true时,我们无法更改location属性,此时location属性的行为将类似于只读。

+1用于说明结构在理想情况下应该是不可变的。奇怪的是<代码>公共整数X{get;set;}
this.Location = new Point(127, 283);
anotherObject.Location = new Point(127, 283);