C# 如何在运行时动态突出显示或更改标签中某些单词的颜色?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1178249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:07:59  来源:igfitidea点击:

How to highlight or change the color of some words in a label dynamically at runtime?

c#.netasp.net

提问by Ahmad Farid

I have a label containing some text and I want to highlight or change the color of some words in the text of the label and not all of the words. It has to be dynamic. Any suggestions?

我有一个包含一些文本的标签,我想突出显示或更改标签文本中某些单词的颜色,而不是所有单词。它必须是动态的。有什么建议?

It's for c# with ASP.NET in a user control in webpart in sharepoint

它适用于 c# 和 ASP.NET 在 sharepoint 中 webpart 的用户控件中

采纳答案by Brian MacKay

On the server-side, you could just embed some Html in your Label's text (VB):

在服务器端,您可以在标签的文本 (VB) 中嵌入一些 Html:

myLabel.Text="Some normal text <span style='color: red;'>some red text</span>"

That's the basic mechanism, but 'dynamic' could mean a lot of things here. If you post some more details about exactly what you're doing, I might be able to help more.

这是基本机制,但“动态”在这里可能意味着很多东西。如果您发布有关您正在做什么的更多详细信息,我可能会提供更多帮助。

One more thought: as Rob Allen pointed out, the Literal control may be a slightly better choice in this situation since it's intended to emit raw Html, whereas the Label wraps the text in a span so that the whole thing can be formatted easily.

还有一个想法:正如 Rob Allen 所指出的,在这种情况下,Literal 控件可能是更好的选择,因为它旨在发出原始 Html,而 Label 将文本包装在一个跨度中,以便可以轻松地设置整个内容的格式。

Check this out for more details: StackOverflow: Literals versus Labels

查看更多详细信息:StackOverflow:文字与标签

For the record, depending on the situation I think a Label may actually be okay here.

为了记录,根据情况,我认为 Label 在这里实际上可能没问题。

回答by Russ Cam

For ASP.NET,

对于 ASP.NET,

wrap the words you want highlighted in a <span>. Then set the <span>style background-colorto the colour of your choice, or use a CSS class to do so.

将要突出显示的单词包裹在<span>. 然后将<span>样式设置background-color为您选择的颜色,或使用 CSS 类来执行此操作。

For example,

例如,

<asp:Label runat="server">
    <span style="background-color:Blue;">Hello</span> World
</asp:Label>

or

或者

<asp:Label runat="server" Text="<span style='background-color:Blue;'>Hello</span> World" />

EDIT:

编辑:

If setting this in code behind, then you can do something like the following

如果在后面的代码中设置它,那么您可以执行以下操作

 StringBuilder builder = new StringBuilder();
 builder.Append([start of text]);
 builder.Append("<span style=\"background-color:Blue;\">");
 builder.Append([text to highlight]);
 builder.Append("</span>");
 builder.Append([rest of text]);

 Label.Text = builder.ToString();

If you needed to match text already in the label against some specific text then something like the following

如果您需要将标签中已有的文本与某些特定文本进行匹配,则类似于以下内容

 string theTextToMatch = "[Text to match]";
 string theText = Label.Text;

 int leftIndex = theText.IndexOf(theTextToMatch, StringComparison.OrdinalIgnoreCase);
 int rightIndex = leftIndex + theTextToMatch.Trim().Length;

 StringBuilder builder = new StringBuilder();
 builder.Append(theText , 0, leftIndex);
 builder.Append("<span style=\"background-color:Blue;\">");
 builder.Append(theText, leftIndex, rightIndex - leftIndex);
 builder.Append("</span>");
 builder.Append(theText, rightIndex, theText.Length - rightIndex);

 Label.Text = builder.ToString();

回答by kemiller2002

If it is asp.net (since you didn't specify) you are referring to you are going have to embed the words you want to highlight in another label.

如果它是 asp.net(因为您没有指定),则您所指的是您必须将要突出显示的单词嵌入另一个标签中。

    <asp:label runat="server" id="nonRed">some text 
        <asp:label runat="server" id="redText" style="color:Red">Red Text</asp:label>
   </asp:label>

回答by Matt Ball

You're going to need to be a lot more specific. What language is this in? Are you building an ASP.NET web site with C# code-behind? Is this label in a Windows Form? Please provide as much detail as you can, and update the tags on your post as well.

你将需要更加具体。这是什么语言?您是否正在使用 C# 代码隐藏构建 ASP.NET 网站?此标签是否在 Windows 窗体中?请提供尽可能多的详细信息,并更新帖子上的标签。

回答by Denis Sadowski

Starting with:

从...开始:

<label> She sells sea shells by the sea shore </label>

We want "sells sea" to be red, and "the sea shore" to be highlighted.

我们要“卖海”是红色的,要突出“海边”。

<label> She <font color="red">sea shells</font> by <font style="BACKGROUND-COLOR: yellow">the sea shore</font></label>

All done!

全部完成!

回答by Greg

You could use a Substitution controlif caching is a concern.

如果缓存是一个问题,您可以使用Substitution 控件

<asp:Label ID="Label1" runat="server" Text="">
    <asp:Substitution ID="Substitution1" runat="server" MethodName="GetDynamicLabel"/>
</asp:Label>

protected static string GetDynamicLabel( HttpContext context )
{
    return string.Format( "<span style='background-color:Blue;'>{0}</span> {1}", "Blue", "Not Blue" );
}

回答by Anastacio Ham

I made a function to look up words in a text string and highlight them with color, the result is put into a label.

我做了一个函数来查找文本字符串中的单词并用颜色突出显示它们,结果被放入标签中。

Function Remarcar(ByVal palabra As String, ByVal texto As String) As String

    Dim textoNuevo As String = String.Empty

    If Not String.IsNullOrEmpty(palabra) Then
        Dim split As String() = texto.Split(New Char() {" "c})

        For Each str As String In split
            If str.ToLower.Contains(palabra.ToLower) Then

                Dim a As String = String.Empty
                Dim b As Int32

                For i = 0 To str.Length
                    If str.ToLower.Substring(i, palabra.Length) = palabra.ToLower Then
                        a = str.Substring(i, palabra.Length)
                        b = i
                        Exit For
                    End If
                Next

                textoNuevo &= str & " "

                textoNuevo = textoNuevo.Replace(str.Substring(b, palabra.Length), "<span style=""background-color:Yellow;"">" & a & "</span>")
            Else
                textoNuevo &= str & " "
            End If
        Next
    Else
        textoNuevo = texto
    End If

    Return textoNuevo
End Function





        Dim texto As String = "I made a function to look up words in a text string and highlight them with color, the result is put into a label."

        Label1.Text = Remarcar("highlight", texto)