设置具有相同文本的多个标签

时间:2017-02-28 09:00:33

标签: c# asp.net localization

我们通过以下方式进行国际化(sp?):

<asp:Label ID="labelPhone" runat="server"></asp:Label>

然后在aspx.cs中:

labelPhone.Text = (string)GetGlobalResourceObject("lang", "Phone") + ":";

但是如果有更多标签我必须重复:

labelPhone2.Text = (string)GetGlobalResourceObject("lang", "Phone") + ":";
labelPhone3.Text = (string)GetGlobalResourceObject("lang", "Phone") + ":";

这可以避免吗?

就像jQuery为所有标识符标签提供相同的类,然后将文本分配给该类:

 $(".phonelabel").text("Telefon:");

3 个答案:

答案 0 :(得分:0)

在C#中,您可以执行单个语句分配,如下所示:

labelPhone.Text = labelPhone2.Text = labelPhone3.Text =
(string)GetGlobalResourceObject("lang", "Phone") + ":";

或者您可以循环执行:

Label[] labels = new[] { labelPhone, labelPhone2, labelPhone3 };
Array.ForEach(labels, x => { x.Text = 
          (string)GetGlobalResourceObject("lang", "Phone") + ":"; });

答案 1 :(得分:0)

你可以使用这种扩展方法。

public static class ControlExtensions
{
    public static void ForControls<T>(this Control ctrl, Func<T, bool> where, Action<T> action) where T : Control
    {
        if (ctrl is T)
            if (where(ctrl as T))
                action(ctrl as T);
        foreach (Control childControl in ctrl.Controls)
        {
            childControl.ForControls(where, action);
        }
    }
}

使用..

            this.ForControls<Label>(
            // you can define any other condition
            c => c.ID.StartsWith("labelPhone"),
            // you can make any other process for this controll
            c => c.Text = (string)GetGlobalResourceObject("lang", "Phone") + ":");

答案 2 :(得分:0)

Panagiotis写道:

 <asp:Label runat="server" Text="<%$ Resources:Lang, Phone %> "  CssClass="box" />

如果评论是答案,我会选择它作为胜利者; - )