2012-03-25 51 views
4

我想在自定義控件中實現一個AutoSize屬性(而不是用戶控件),其行爲與在設計模式下實現AutoSize(ala CheckBox)的其他標準.NET WinForms控件一樣。如何實現自定義控件的AutoSize屬性?

我有屬性設置,但它是控制在設計模式下的行爲方式使我感到困惑。 它仍然可以調整大小,這是沒有意義的,因爲視覺大小不會反映在我已經實現的AutoSize和Size屬性中。

當AutoSize爲true時,標準.NET控件不允許在設計模式下調整大小(甚至不顯示調整大小手柄)。我希望我的控制行爲以相同的方式進行。

編輯:我有工作使用SetBoundsCore()重寫,但它不會在視覺上限制調整大小時自動調整大小設置爲true,它只是有同樣的效果;功能相同,但感覺不自然。

protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) 
{ 
    if (!this.auto_size) 
     this.size = new Size(width, height); 
    base.SetBoundsCore(x, y, this.size.Width, this.size.Height, specified); 
} 

這樣做的標準方式的任何想法?

+0

你使用的是什麼UI庫?的WinForms? WPF? ASP.NET?還有別的嗎? – svick 2012-03-25 00:55:30

+0

Winforms,編輯在=] – mina 2012-03-25 01:11:31

+0

你嘗試添加sizechanged事件,並把你的調整大小邏輯? – Oztaco 2012-03-25 04:14:04

回答

0

在您的控件的構造函數中,調用SetAutoSizeMode(AutoSizeMode.GrowAndShrink)。

0

重寫SizeFromClientSize()方法。在這種方法中,您必須計算所需控件的大小並將其返回。

3

這裏是我的食譜,有你的控制AutoSize。

創建一個方法GetAutoSize()根據您的具體實現計算所需的控件大小。也許是它包含的文本的大小或當前寬度的控件的總高度,無論如何。

創建一個方法ResizeForAutoSize()來強制控件在其狀態發生更改後調整其自身大小。例如,如果控件的大小適合其包含的文本,則更改文本應該調整控件的大小。在文本更改時調用此方法。

重寫GetPreferredSize()以通知任何想知道的人(例如FlowLayoutPanel)我們的首選大小。

重寫SetBoundsCore()以強制我們的大小調整規則,這與AutoSize標籤不能調整大小的方式相同。

請在此處查看示例。

/// <summary> 
/// Method that forces the control to resize itself when in AutoSize following 
/// a change in its state that affect the size. 
/// </summary> 
private void ResizeForAutoSize() 
{ 
    if(this.AutoSize) 
     this.SetBoundsCore(this.Left, this.Top, this.Width, this.Height, 
        BoundsSpecified.Size); 
} 

/// <summary> 
/// Calculate the required size of the control if in AutoSize. 
/// </summary> 
/// <returns>Size.</returns> 
private Size GetAutoSize() 
{ 
    // Do your specific calculation here... 
    Size size = new Size(100, 20); 

    return size; 
} 

/// <summary> 
/// Retrieves the size of a rectangular area into which 
/// a control can be fitted. 
/// </summary> 
public override Size GetPreferredSize(Size proposedSize) 
{ 
    return GetAutoSize(); 
} 

/// <summary> 
/// Performs the work of setting the specified bounds of this control. 
/// </summary> 
protected override void SetBoundsCore(int x, int y, int width, int height, 
     BoundsSpecified specified) 
{ 
    // Only when the size is affected... 
    if(this.AutoSize && (specified & BoundsSpecified.Size) != 0) 
    { 
     Size size = GetAutoSize(); 

     width = size.Width; 
     height = size.Height; 
    } 

    base.SetBoundsCore(x, y, width, height, specified); 
}