自定义文本框更改背景色时只读

本文关键字:背景色 只读 文本 自定义 | 更新日期: 2023-09-27 18:06:57

嗨,我有一个自定义的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,但它不工作。

什么线索吗?

自定义文本框更改背景色时只读

你是在构造函数上做的。哪个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);
    }
}