You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为项目中所有TextBox控件添加GotFocus、LostFocus事件?

WinForm 项目实现方案
  • 首先编写通用的焦点事件处理方法,所有TextBox的事件都会共用这两个逻辑:
private void TextBox_GotFocus(object sender, EventArgs e)
{
    if (sender is TextBox tb)
    {
        // 自定义聚焦状态背景色
        tb.BackColor = Color.LightYellow;
    }
}

private void TextBox_LostFocus(object sender, EventArgs e)
{
    if (sender is TextBox tb)
    {
        // 恢复默认背景色
        tb.BackColor = SystemColors.Window;
    }
}
  • 编写递归绑定方法,遍历所有层级的控件自动绑定事件:
private void BindTextBoxEvents(Control.ControlCollection controls)
{
    foreach (Control control in controls)
    {
        // 匹配TextBox控件并绑定事件
        if (control is TextBox tb)
        {
            tb.GotFocus += TextBox_GotFocus;
            tb.LostFocus += TextBox_LostFocus;
        }
        // 递归遍历嵌套子控件
        if (control.HasChildren)
        {
            BindTextBoxEvents(control.Controls);
        }
    }
}
  • 在每个窗体的Load事件中调用BindTextBoxEvents(this.Controls)即可完成当前窗体所有TextBox的事件绑定,后续动态生成的TextBox在创建后调用一次该方法绑定即可。如果需要全局生效,也可以封装为窗体基类的通用逻辑,所有窗体继承该基类就不用逐个写调用代码。

WPF 项目实现方案

不需要写事件绑定代码,直接用全局样式即可实现,在App.xaml的资源节点中添加如下配置:

<Application.Resources>
    <Style TargetType="TextBox">
        <Style.Triggers>
            <Trigger Property="IsFocused" Value="True">
                <Setter Property="Background" Value="LightYellow"/>
            </Trigger>
            <Trigger Property="IsFocused" Value="False">
                <Setter Property="Background" Value="White"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Application.Resources>

该样式会自动应用到项目内所有未单独设置Style属性的TextBox控件,如果部分TextBox不需要该效果,单独给这些控件设置自定义Style覆盖全局规则即可。

内容的提问来源于stack exchange,提问作者Hamada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:57:04