我可以改变字符串一部分的字体颜色吗?

本文关键字:颜色 字体 改变 字符串 一部分 我可以 | 更新日期: 2023-09-27 18:15:48

我可以更改以下字符串中m_pwdm_senior所代表的部分的颜色吗?

string m_pwd = "PWD";
string m_senior = "Senior";
lblMarquee.Text = "Hi" + m_senior + "and" + m_pwd;

我可以改变字符串一部分的字体颜色吗?

你不能改变字符串的"颜色",就像你不能改变数字、列表或其他简单存储值的数据类型的颜色一样。

您需要做的是修改该数据的可视化表示,在本例中是Label控件。从Control派生的任何东西都具有可用的ForeColorBackColor属性。

在WinForms中做你需要的一个简单的方法是在Panel中分组几个标签彼此相邻,根据需要更改每个标签的颜色,然后根据需要操作Panel作为一个单独的实体。

您应该创建几个不同颜色的标签来创建它。如果您的目标是隐藏/显示标签以方便操作,则可以使用面板。

Label控件一次只支持一个ForeColor。如果你需要同时处理一种以上的颜色,你可以设置一个水平流动的FlowLayoutPanel,然后在其中包括多个Label,按你选择的颜色。从编程的角度来说,这不是世界上最漂亮的解决方案,但我相信它应该适合你。

我说使用FlowLayoutPanel而不是Panel,因为这将允许您使用可变长度字符串而不用担心定位。

本质上,做这样的事情。当然,Control的创建通常发生在设计器中。但是你可以看到它是如何工作的。

FlowLayoutPanel flp = new FlowLayoutPanel();
Label lblA = new Label();
lblA.Text = "Hi ";
flp.Controls.Add(lblA);
Label lblB = new Label();
lblB.Text = m_senior;
lblB.ForeColor = Color.Red;
flp.Controls.Add(lblB);
Label lblC = new Label();
lblC.Text = " and "; // The spaces for this and "Hi " may or may not be necessary. They are in theory, but it's mostly dependent on the margins of the Labels. Just check which looks best.
flp.Controls.Add(lblC);
Label lblD = new Label();
lblD.Text = m_pwd;
lblD.ForeColor = Color.Red;
flp.Controls.Add(lblD);

类似于上面提供的Matthew Haugen的答案,使用流布局面板。但是在我的示例中,标签的创建是动态完成的。通过应用任何Split字符串并区分您想要着色的文本和不希望着色的文本,这是很有用的。

FlowLayoutPanel flowPanel = new FlowLayoutPanel();
        string m_pwd = "PWD";
        string m_senior = "Senior";
        string toBeColored = "Hi " + m_senior + " and " + m_pwd;
        string[] splitColored = toBeColored.Split(' ');
        foreach (string s in splitColored)
        {
            Label l = new Label();
            l.Text = s;
            if (s == m_pwd)
            {
                l.ForeColor = Color.Red;
            }
            else if (s == m_senior)
            {
                l.ForeColor = Color.Blue;
            }
            flowPanel.Controls.Add(l);
        }
        this.Controls.Add(flowPanel); //was missing from earlier example 

注意:为了使它在视觉上令人愉悦,我建议根据你的应用程序调整流布局面板的大小

这是我的,但这是为了选框的目的

      lbl_PWD.ForeColor = Color.Red;
        lbl_senior.ForeColor = Color.Red;
        if (panel1.Right > 0)
        {
            panel1.Left = panel1.Left - 5;
        }
        else if (panel1.Right <= 0)
        {
            panel1.Left = this.Width;
        }