2017-06-13 51 views
0

後,我有我想要做一個自定義的文本框的一個問題:C#默認值重置自身建設

我試圖創建的真默認值一個新的屬性,讓文本框後調整本身textChanged,但每次我生成項目,即使我手動將屬性窗口中的值更改爲false,該屬性的值會將其自身重置爲true。

[Browsable(true)] 
    new public bool AutoSize { get; set; } = true; 

    protected override void OnTextChanged(EventArgs e) 
    { 
     if (AutoSize == true) 
     { 
      Size size = TextRenderer.MeasureText(Text, Font); 
      Width = size.Width; 
      Height = size.Height; 
     } 
     base.OnTextChanged(e); 
    } 

回答

0

嘗試具有支持字段和使用:

private bool _AutoSize = true; 

    [Browsable(true)] 
    new public bool AutoSize 
    { 
     get { return _AutoSize; } 
     set 
     { 
      _AutoSize = value; 
      UpdateStyles(); 
     } 
    } 
+0

已經嘗試過,不起作用,請在這裏閱讀https://support.microsoft.com/it-it/help/311339/msdn-documentation-for-the-defaultvalueattribute-class-may-be-confusing – Signum

+0

@ Signum看到我編輯的答案 – CodingYoshi

+0

試過,即使那個,沒有結果 – Signum

0
public class SampleEx : TextBox 
    { 
     [Browsable(true)] 
     [DefaultValue(typeof(bool), "true")] 
     new public bool AutoSize { get; set; } 

     public SampleEx() 
      : base() 
     { 
      this.AutoSize = true;    
     } 
    } 

在[默認值(typeof運算(布爾), 「真」),你必須構造函數來設置爲true。 它會爲你工作。

+0

這也可以,謝謝 – Signum