VAAA VAAA - 2 months ago 30
C# Question

Winform - Custom TextBox change backcolor when Readonly

Hi I have a custom

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);
}
}


I would like to change its
BackGroundColor
when the property
ReadOnly = true
but its not working.


Any clue?

Bob Bob
Answer

You are doing it on constructor. Which ReadOnly be default to False

What you need is listen to ReadOnlyChanged event

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);
    }
}
Comments