c# - 带格式化文本字段的标签/文字控件

标签 c# asp.net string.format

我发现可以使用 string.format 用变量信息填充资源字符串,见下文:

String.Format(Resources.Temp.TempString, Resources.Contact.PhoneSales)

我可以使用以下方法在我的页面上显示它:

<p><%= String.Format(Resources.Temp.TempString, Resources.Contact.PhoneSales) %></p>

在某些情况下,我有一个可能动态隐藏或显示内容的标签或文字(或任何控件)。通常我会填充那些使用:

<asp:Literal ID="Literal1" Text="<%$ Resources:Temp,ContactUs %>" runat="server" />

我现在想要相同的 String.Format 功能,同时仍然使用控件。我找到了 Display value of Resource without Label or Literal control但这实际上对我不起作用,它只是在页面上写出 '<%= GetGlobalResourceObject("Messages", "ThankYouLabel") %>'(不是内容,是实际的字符串)。

更新:

我找到了一个适用于某些控件的解决方案:

<asp:Label runat="server" ID="temp"><%= String.Format(Resources.Temp.TempString, Resources.Contact.PhoneSales) %></asp:Label>

但是,这对 Literal 控件不起作用,因为它们不允许子控件。我更愿意继续使用 Literal,因为它们在生成的代码方面是最干净的,所以仍在寻求解决方案。

最佳答案

asp:Literal不支持 <%= %>构造,并且不允许子控件(我的意思是像 <asp:Literal runat="server"><%= ... %></asp:Literal> )。

但是如果你使用数据绑定(bind),你可以使用 data-binding expresions <%# ... %> :

<asp:Label runat="server" Text="<%# string.Format(...) %>"></asp:Label>

要完成这项工作,您应该确保为您的控件使用隐式或显式数据绑定(bind)。否则像这样没有绑定(bind)的控件不输出任何内容

此解决方法有点复杂。考虑使用 asp:Label控制,或设置 Text来自代码背后的属性。

关于c# - 带格式化文本字段的标签/文字控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9994143/

相关文章:

c# - Azure 事件日志 - TargetInitationException 和奇怪的消息

c# - 如何在 C# 中以编程方式连接 ToolStripButton 事件?

asp.net - 如何在 Epplus 中使用条件格式?

c# - log4net(common.logging)错误异常

C# 对象初始化选项

c# - 在 C# 中使用 Arcsin 计算正交三角形的角度

asp.net - 用户退出我在 WinHost 上托管的 MVC3 应用程序

c# - 如何在 asp.net 中使用 Windows 身份验证获取用户名?

c# - 从代码隐藏格式化 DataGridTextColumn

java - 如何让 string.format 在编译时报错