【问题标题】:C# WInforms Change border style on button click eventC# WInforms 在按钮单击事件上更改边框样式
【发布时间】:2015-05-28 08:06:36
【问题描述】:

我正在尝试在按钮单击事件上更改文本框 (txtUser) 的边框颜色(类似于表单验证,如果输入为空,则调用将边框着色为红色的方法)。我做了一些谷歌搜索,发现了这个:

void myControl1_Paint(object sender, PaintEventArgs e)
{
ControlPaint.DrawBorder(e.Graphics, this.txtUser.ClientRectangle, Color.Black, ButtonBorderStyle.Solid);
}

但我无法理解我应该在哪里或如何调用此方法,或以 (object sender, PaintEventArgs e) 作为参数的方法。任何解释表示赞赏。

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    您需要从 TextBox 继承,然后重写 OnPaint 方法。这样的事情应该可以工作:

    public class ValidateEdit : TextBox
    {
        bool _InError;
    
        public ValidateEdit()
        {
            SetStyle(ControlStyles.UserPaint, true);
        }
    
        public bool InError {
            get {
                return _InError;
            }
            set
            {
                _InError = value;
                Refresh();
            }
        }
    
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            if (InError)
                ControlPaint.DrawBorder(e.Graphics, this.DisplayRectangle, Color.Red, ButtonBorderStyle.Solid);
        }
    }
    

    【讨论】:

    • 可以对事件执行此操作,而无需创建自己的控件。上述答案的相关部分是 InError 代码,您可以通过验证事件进行切换。拥有一个继承的文本框确实会为您将属性直接添加到控件中,这使得管理变得更容易和更好的 OO 实践。
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-17
    • 2015-10-14
    • 1970-01-01
    相关资源
    最近更新 更多