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

Aho*_*tbi 38 c# controls runtime visual-studio-2010 winforms

我尝试了以下代码:

 this.balancePanel.Location.X = this.optionsPanel.Location.X;
Run Code Online (Sandbox Code Playgroud)

在程序运行时更改我在设计模式下创建的面板的位置但它返回错误:

Cannot modify the return value of 'System.Windows.Forms.Control.Location' because it is not a variable
Run Code Online (Sandbox Code Playgroud)

所以问题是我该怎么做?

Mar*_*ers 64

Location属性的类型Point是结构.

Point尝试分配新Point对象,而不是尝试修改现有对象:

 this.balancePanel.Location = new Point(
     this.optionsPanel.Location.X,
     this.balancePanel.Location.Y
 );
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 15

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

this.balancePanel.Location = new Point(
    this.optionsPanel.Location.X,
    this.balancePanel.Location.Y);
Run Code Online (Sandbox Code Playgroud)

大多数结构也是不可变的,但在罕见(且令人困惑)的情况下,它是可变的,你也可以复制,编辑,复制;

var loc = this.balancePanel.Location;
loc.X = this.optionsPanel.Location.X;
this.balancePanel.Location = loc;
Run Code Online (Sandbox Code Playgroud)

虽然我不推荐上述内容,但结构理想情况下应该是不可变的.

  • +1 提到结构在理想情况下应该是不可变的。奇怪的是...... `public int X { get; 放; }` http://msdn.microsoft.com/en-us/library/system.drawing.point.x.aspx (2认同)

shf*_*301 8

使用:

balancePanel.Left = optionsPanel.Location.X

要么

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

请参阅位置文档:

因为Point类是值类型(Visual Basic中的结构,Visual C#中的struct),所以它是按值返回的,这意味着访问该属性会返回控件左上角的副本.因此,调整从此属性返回的Point的X或Y属性不会影响控件的Left,Right,Top或Bottom属性值.要调整这些属性,请单独设置每个属性值,或者使用新Point设置Location属性.


bag*_*man 5

如果由于某种原因balancePanel不起作用,你可以使用这个:

this.Location = new Point(127, 283);
Run Code Online (Sandbox Code Playgroud)

或者

anotherObject.Location = new Point(127, 283);
Run Code Online (Sandbox Code Playgroud)