MudBlazor中MudToolTip文本添加换行的方法咨询
MudBlazor中MudTooltip文本换行的解决方法
方法一:用Html属性替代Text属性
MudTooltip的Text属性会把内容当作纯文本渲染,换行符会被浏览器忽略。改用Html属性,把换行符替换成<br>标签就能实现换行:
<MudTooltip Html="@formattedToolTip"> <MudButton>悬停查看多行提示</MudButton> </MudTooltip> @code { // 原始带换行的字符串 private string toolTipText = $"第一行文本{System.Environment.NewLine}第二行文本"; // 转换为带<br>的HTML格式字符串 private string formattedToolTip => toolTipText.Replace(System.Environment.NewLine, "<br>"); }
方法二:通过CSS样式识别换行符
给Tooltip的内容容器添加white-space: pre-line样式,让浏览器自动解析换行符为换行:
<MudTooltip Text="@toolTipText" Class="multi-line-tooltip"> <MudButton>悬停查看多行提示</MudButton> </MudTooltip> <style> .multi-line-tooltip .mud-tooltip-content { white-space: pre-line; /* 可选:调整内边距优化排版 */ padding: 8px 12px; } </style> @code { private string toolTipText = $"第一行文本{System.Environment.NewLine}第二行文本"; }
为什么System.Environment.NewLine不生效?
HTML默认会把纯文本里的换行、空格等空白字符合并成单个空格,所以直接用换行符无法触发换行效果。要么用HTML标签强制换行,要么通过CSS属性让浏览器保留换行格式。
内容的提问来源于stack exchange,提问作者Shakil Ahmed
相关产品推荐
相关产品推荐

