C# Change the location of an object programmatically

旧巷老猫 提交于 2019-12-25 01:49:08

问题


I Tried the following code:

 this.balancePanel.Location.X = this.optionsPanel.Location.X;

to change the location of a panel that I made in design mode while the program is running but it returns an error:

Cannot modify the return value of 'System.Windows.Forms.Control.Location' because it is not a variable

So how can I do it?


回答1:


The Location property has type Point which is a struct.

Instead of trying to modify the existing Point, try assigning a new Point object:

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



回答2:


Location is a struct. If there aren't any convenience members, you'll need to reassign the entire Location:

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

Most structs are also immutable, but in the rare (and confusing) case that it is mutable, you can also copy-out, edit, copy-in;

var loc = this.balancePanel.Location;
loc.X = this.optionsPanel.Location.X;
this.balancePanel.Location = loc;

Although I don't recommend the above, since structs should ideally be immutable.




回答3:


Use either:

balancePanel.Left = optionsPanel.Location.X

or

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

See the documentation of Location:

Because the Point class is a value type (Structure in Visual Basic, struct in Visual C#), it is returned by value, meaning accessing the property returns a copy of the upper-left point of the control. So, adjusting the X or Y properties of the Point returned from this property will not affect the Left, Right, Top, or Bottom property values of the control. To adjust these properties set each property value individually, or set the Location property with a new Point.




回答4:


If somehow balancePanel won't work, you could use this:

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

or

anotherObject.Location = new Point(127,283)



回答5:


You need to pass the whole point to location

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



回答6:


When the parent panel has locked property set to true, we could not change the location property and the location property will act like read only by that time.



来源:https://stackoverflow.com/questions/36063694/cannot-modify-the-return-value-of-control-location-because-it-is-not-a-variabl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!