2017-06-13 53 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