2011-12-03 6 views
31

ho provato il seguente codice:C# Modifica della posizione di un oggetto di programmazione

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

per modificare la posizione di un pannello che ho fatto nella modalità di progettazione, mentre il programma è in esecuzione, ma restituisce un errore:

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

quindi la domanda è come posso farlo?

risposta

53

La proprietà Location ha il tipo Point che è una struttura.

Invece di cercare di modificare l'esistente Point, provate ad assegnare un nuovo Point oggetto:

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

grazie mark, ha funzionato come un fascino –

1

il necessario per passare il punto di posizione

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

posizione è una struct. Se non ci sono i membri di convenienza, è necessario riassegnare l'intera Località:

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

maggior parte le strutture sono anche immutabili, ma nel raro (e confuso) caso che è mutevole, è anche possibile copiare -out, modifica, copia-in;

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

Anche se non consiglio quanto sopra, dal momento che le strutture dovrebbero idealmente essere immutabili.

+1

+1 per aver menzionato che le strutture dovrebbero idealmente essere immutabili. Stranamente però ... 'public int X {get; impostato; } 'http://msdn.microsoft.com/en-us/library/system.drawing.point.x.aspx –

7

utilizzare:

balancePanel.Left = optionsPanel.Location.X

o

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

Vedere il 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

Se in qualche modo balancePanel non funziona, si potrebbe usare questo:

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

o

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

Quando il pannello genitore ha bloccato insieme di proprietà su true, non abbiamo potuto modificare la proprietà posizione e la proprietà location agirà come letto solo da quel momento.