2011-12-03 23 views
31

He probado el siguiente código:C# cambiar la ubicación de un objeto mediante programación

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

para cambiar la ubicación de un panel que hice en el modo de diseño, mientras que el programa se está ejecutando, pero devuelve un error:

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

así que la pregunta es ¿cómo puedo hacerlo?

Respuesta

53

La propiedad Location tiene el tipo Point que es una estructura.

En lugar de tratar de modificar el Point existente, intente asignar un nuevo objeto Point:

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

gracias, funcionó como un amuleto –

1

lo necesario para aprobar el punto de ubicación

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

ubicación es una estructura. Si no hay miembros de conveniencia, tendrá que volver a asignar la totalidad del Lugar:

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

La mayoría de estructuras también son inmutables, pero en el caso raro (y confusa) que es mutable, también se puede copiar -out, edit, copy-in;

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

Aunque no recomiendo lo anterior, ya que las estructuras deberían ser inmutables.

+1

+1 por mencionar que las estructuras idealmente deberían ser inmutables. Por extraño que parezca ... 'public int X {get; conjunto; } 'http://msdn.microsoft.com/en-us/library/system.drawing.point.x.aspx –

7

uso ya sea:

balancePanel.Left = optionsPanel.Location.X

o

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

Véase el 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.

2

Si de alguna manera balancePanel no va a funcionar, usted podría utilizar esto:

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

o

anotherObject.Location = new Point(127,283) 
0

Cuando el panel de los padres ha bloqueado propiedad establecida en true, que no podíamos cambiar la propiedad ubicación y la propiedad de ubicación actuará como sólo lectura en ese momento.

Cuestiones relacionadas