Winform - 自定义TextBox在Readonly时更改背景色

时间:2016-09-14 01:21:59

标签: c# winforms

您好我有自定义TextEditor

 public partial class TextEditor : TextBox
    {
        public TextEditor() : base()
        {
            this.Font = new Font("Calibri", 12.0f);
            this.BackColor = Color.Gainsboro;
            this.BorderStyle = BorderStyle.FixedSingle;

            if (this.ReadOnly)
            {
                this.BackColor = Color.DarkGray;
            }

        }

        protected override void InitLayout()
        {
            base.InitLayout();
            base.CharacterCasing = _charCasing;
            //SetStyle(ControlStyles.UserPaint, true);
        }
}

我想在属性BackGroundColor时更改ReadOnly = true,但它无效。

  

有任何线索吗?

1 个答案:

答案 0 :(得分:0)

你是在构造函数上做的。哪个ReadOnly默认为False

您需要的是听取ReadOnlyChanged事件

public partial class TextEditor : TextBox
{
    public TextEditor()
    {
        this.Font = new Font("Calibri", 12.0f);
        this.BackColor = Color.Gainsboro;
        this.BorderStyle = BorderStyle.FixedSingle;

        ReadOnlyChanged += OnReadOnlyChanged;
    }

    private void OnReadOnlyChanged(object sender, EventArgs eventArgs)
    {
        if (ReadOnly)
            BackColor = Color.DarkGray;
    }

    protected override void InitLayout()
    {
        base.InitLayout();
        CharacterCasing = _charCasing;
        //SetStyle(ControlStyles.UserPaint, true);
    }
}