Change the location of an object programmatically

前端 未结 6 857
南笙
南笙 2020-12-01 12:19

I\'ve tried the following code:

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

to change the location of a panel that I mad

相关标签:
6条回答
  • 2020-12-01 12:24

    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.

    0 讨论(0)
  • 2020-12-01 12:28

    You need to pass the whole point to location

    var point = new Point(50, 100);
    this.balancePanel.Location = point;
    
    0 讨论(0)
  • 2020-12-01 12:39

    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
     );
    
    0 讨论(0)
  • 2020-12-01 12:44

    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.

    0 讨论(0)
  • 2020-12-01 12:46

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

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

    or

    anotherObject.Location = new Point(127, 283);
    
    0 讨论(0)
  • 2020-12-01 12:47

    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.

    0 讨论(0)
提交回复
热议问题