运行时如何在内部TextBox激活时修改Panel边框颜色?
实现TextBox激活时修改父Panel边框颜色的方案
WinForms 实现方式
Panel默认没有直接的BorderColor属性,我们可以通过自定义绘制边框的方式实现需求:
- 定义变量标记Panel高亮状态
private bool _isPanelHighlighted = false;
- 给Panel添加Paint事件,用于绘制自定义边框
private void panel1_Paint(object sender, PaintEventArgs e) { Color borderColor = _isPanelHighlighted ? Color.RoyalBlue : Color.DarkGray; // 绘制2px宽度的实心边框 ControlPaint.DrawBorder(e.Graphics, panel1.ClientRectangle, borderColor, 2, ButtonBorderStyle.Solid, borderColor, 2, ButtonBorderStyle.Solid, borderColor, 2, ButtonBorderStyle.Solid, borderColor, 2, ButtonBorderStyle.Solid); }
- 给内部TextBox绑定Enter和Leave事件
private void textBox1_Enter(object sender, EventArgs e) { _isPanelHighlighted = true; panel1.Invalidate(); // 触发重绘更新边框颜色 } private void textBox1_Leave(object sender, EventArgs e) { _isPanelHighlighted = false; panel1.Invalidate(); }
如果Panel内有多个TextBox,只需将所有TextBox的Enter/Leave事件绑定到上述方法即可。
WPF 实现方式
WPF的容器控件自带BorderBrush属性,实现更简洁:
- XAML布局代码
<Border x:Name="myPanel" BorderThickness="2" BorderBrush="DarkGray" Padding="10"> <TextBox x:Name="myTextBox" Width="200" Height="30"/> </Border>
注:WPF中常用Border作为带边框的容器,若需使用Panel,可将Panel嵌套在Border内部。
- 后台事件处理代码
private void myTextBox_GotFocus(object sender, RoutedEventArgs e) { myPanel.BorderBrush = new SolidColorBrush(Colors.RoyalBlue); } private void myTextBox_LostFocus(object sender, RoutedEventArgs e) { myPanel.BorderBrush = new SolidColorBrush(Colors.DarkGray); }
内容的提问来源于stack exchange,提问作者George Michael
相关产品推荐
相关产品推荐

