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

如何实现文本框内LogUser变量对应特定文本的加粗显示

实现步骤

普通TextBox控件只支持纯文本展示,无法单独为局部内容设置加粗样式,你需要先根据项目用的UI框架选择对应方案:

WinForm框架(匹配你当前的代码场景)

将txt_logUser替换为RichTextBox控件后,通过设置选中文本的字体格式实现局部加粗,代码如下:

// 清空控件原有内容
txt_logUser.Clear();

// 写入普通样式的前缀文本
txt_logUser.SelectionFont = new Font(txt_logUser.Font, FontStyle.Regular);
txt_logUser.SelectedText = "Logged user is: ";

// 写入加粗样式的用户名内容
txt_logUser.SelectionFont = new Font(txt_logUser.Font, FontStyle.Bold);
txt_logUser.SelectedText = LogUser;

// 重置光标位置和默认字体,避免后续输入继承加粗样式
txt_logUser.SelectionStart = txt_logUser.TextLength;
txt_logUser.SelectionLength = 0;
txt_logUser.SelectionFont = new Font(txt_logUser.Font, FontStyle.Regular);

如果不想替换控件,也可以用两个文本控件并排摆放:一个放普通样式的"Logged user is: "前缀,另一个单独放LogUser内容并设置全局加粗,是更轻量的实现方案。

WPF框架

如果是WPF项目,不需要替换控件,直接给文本控件添加内联元素即可:

txt_logUser.Inlines.Clear();
txt_logUser.Inlines.Add(new Run("Logged user is: "));
txt_logUser.Inlines.Add(new Run(LogUser) { FontWeight = FontWeights.Bold });

注意事项

不要直接给Text属性拼接HTML、RTF标记字符串,普通文本控件不会解析这类格式标记,会直接把标记作为普通文本显示出来。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 01:01:06