Control.Anchor 屬性

定義

取得或設定控制項繫結至的容器邊緣,並決定控制項隨其父代重新調整大小的方式。

C#
public virtual System.Windows.Forms.AnchorStyles Anchor { get; set; }

屬性值

AnchorStyles 值的位元組合。 預設值為 TopLeft

範例

下列程式碼範例會將 新增 Button 至表單,並設定其一些通用屬性。 此範例會將按鈕錨定在表單右下角,讓它在表單調整大小時保留其相對位置。 接下來,它會將 和 按鈕的大小設定 BackgroundImage 為與 Image 相同的大小。 此範例接著會將 TabStop 設定為 true ,並設定 TabIndex 屬性。 最後,它會新增事件處理常式來處理 Click 按鈕的事件。 此範例需要您有 ImageList 名為 imageList1 的 。

C#
// Add a button to a form and set some of its common properties.
private void AddMyButton()
{
   // Create a button and add it to the form.
   Button button1 = new Button();

   // Anchor the button to the bottom right corner of the form
   button1.Anchor = (AnchorStyles.Bottom | AnchorStyles.Right);

   // Assign a background image.
   button1.BackgroundImage = imageList1.Images[0];

   // Specify the layout style of the background image. Tile is the default.
   button1.BackgroundImageLayout = ImageLayout.Center;
   
   // Make the button the same size as the image.
   button1.Size = button1.BackgroundImage.Size;

   // Set the button's TabIndex and TabStop properties.
   button1.TabIndex = 1;
   button1.TabStop = true;

   // Add a delegate to handle the Click event.
   button1.Click += new System.EventHandler(this.button1_Click);

   // Add the button to the form.
   this.Controls.Add(button1);
}

備註

Anchor使用 屬性來定義當控制項的父控制項調整大小時,控制項自動調整大小的方式。 將控制項錨定至其父控制項,可確保錨定邊緣在調整父控制項大小時,與父控制項邊緣相對的相同位置。

您可以將控制項錨定在其容器的一或多個邊緣。 例如,如果您有 FormButton 的 ,其 Anchor 屬性值設定為 TopBottom ,則會 Button 延展 ,以在 增加 時 FormHeight ,維持與 上邊緣和下邊緣的 Form 錨定距離。

注意

AnchorDock 屬性互斥。 一次只能設定一個,最後一個集合優先。

給繼承者的注意事項

在衍生類別中覆 Anchor 寫 屬性時,請使用基類的 Anchor 屬性來擴充基底實作。 否則,您必須提供所有實作。 您不需要同時覆寫 get 屬性的 Anchorset 存取子;您可以視需要只覆寫一個。

適用於

產品 版本
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

另請參閱