Blazor Razor文件中C#属性无法绑定到SVG textPath的问题咨询
问题:Blazor中SVG文本绕圆绑定C#属性后不显示
在Razor文件中实现SVG文本绕圆效果时,硬编码文本可正常显示,但将textPath内的文本替换为C#属性@text后,文本完全不显示。
正常运行的代码:
<svg> <path id="circle" d="m96.06557,140.16394c-27.62431,0 -50,-22.37569 -50,-50c0,-27.62431 22.37569,-50 50,-50c27.62431,0 48.85246,22.37569 48.85246,50c0,27.62431 -21.22815,50 -48.85246,50z" /> <text transform="rotate(155 95.4918 90.1639)"> <textPath xlink:href="#circle"> EXPECTED RESULT </textPath> </text> </svg>
绑定C#属性后无文本显示的代码:
<svg> <path id="circle" d="m96.06557,140.16394c-27.62431,0 -50,-22.37569 -50,-50c0,-27.62431 22.37569,-50 50,-50c27.62431,0 48.85246,22.37569 48.85246,50c0,27.62431 -21.22815,50 -48.85246,50z" /> <text transform="rotate(155 95.4918 90.1639)"> <textPath xlink:href="#circle"> @text </textPath> </text> </svg>
解决方案
1. 修正SVG属性命名空间
将xlink:href替换为标准的href属性(SVG2已废弃xlink命名空间,现代浏览器均支持直接使用href),避免Blazor解析SVG元素时出现异常。
2. 确保C#属性可访问
在组件的@code块中定义公共属性并初始化值:
@code { public string text { get; set; } = "你的绑定文本内容"; }
3. 正确使用Razor文本绑定
在textPath内部直接使用@text即可,若文本包含特殊字符,可使用@Html.Raw(text)确保正常渲染。
修改后的完整代码:
<svg> <path id="circle" d="m96.06557,140.16394c-27.62431,0 -50,-22.37569 -50,-50c0,-27.62431 22.37569,-50 50,-50c27.62431,0 48.85246,22.37569 48.85246,50c0,27.62431 -21.22815,50 -48.85246,50z" /> <text transform="rotate(155 95.4918 90.1639)"> <textPath href="#circle"> @text </textPath> </text> </svg> @code { public string text { get; set; } = "绑定成功的绕圆文本"; }
内容的提问来源于stack exchange,提问作者myrlejon
相关产品推荐
相关产品推荐

