【问题标题】:label1 property join label2 propertylabel1 属性连接 label2 属性
【发布时间】:2017-02-09 08:01:32
【问题描述】:

label1 text&property 和 label2 text&property 可以合二为一,在label3中显示并添加文字=吗?因为我现在使用的是label1label2 并排使用。

告诉我是否有其他方法

Ps:我在 redblue 等数据库中定义颜色。

【问题讨论】:

  • 当你说组合属性时......哪些?

标签: c# winforms


【解决方案1】:

您可以像这样组合文本内容:

label3.Text = label1.Text + " = " + label2.Text;

但是你会失去不同的颜色。不幸的是,这是不可能的。更多详情请查看this answer

【讨论】:

  • 好的,谢谢您的确认。我只需要知道是否可以将 2 属性标签加入 1
【解决方案2】:

使用 string.format 将 2 个标签文本组合在一起。

label3.Text = string.Format("{0}={1}", label1.Text, label2.Text);

【讨论】:

    【解决方案3】:

    为什么要投反对票¿

    您可以将自己的文本图像写入您的标签3。喜欢here

    和。

    首先设置 label3 AutoSize = false 并设置大小。

        // Add this lines to InitializeComponent() in yourform.Designer.cs
        this.label1.TextChanged += new System.EventHandler(this.label_TextChanged);
        this.label2.TextChanged += new System.EventHandler(this.label_TextChanged);
    
    
        // this is label1 and label2 TextCahanged Event
        private void label_TextChanged(object sender, EventArgs e)
        {
            SetMultiColorText(string.Format("{0} = {1}", label1.Text, label2.Text),label3);
        }
    
    // this method set multi color image text for label(paramter lb)
        public void SetMultiColorText(string Text, Label lb)
        {
            lb.Text = "";
            // PictureBox needs an image to draw on
            lb.Image = new Bitmap(lb.Width, lb.Height);
            using (Graphics g = Graphics.FromImage(lb.Image))
            {
    
    
                SolidBrush brush = new SolidBrush(Form.DefaultBackColor);
                g.FillRectangle(brush, 0, 0,
                    lb.Image.Width, lb.Image.Height);
    
                string[] chunks = Text.Split('=');
                brush = new SolidBrush(Color.Black);
    
                // you can get this colors from label1 and label2 colors... or from db.. or an other where you want
                SolidBrush[] brushes = new SolidBrush[] { 
            new SolidBrush(Color.Black),
            new SolidBrush(Color.Red) };
                float x = 0;
                for (int i = 0; i < chunks.Length; i++)
                {
                    // draw text in whatever color
                    g.DrawString(chunks[i], lb.Font, brushes[i], x, 0);
                    // measure text and advance x
                    x += (g.MeasureString(chunks[i], lb.Font)).Width;
                    // draw the comma back in, in black
                    if (i < (chunks.Length - 1))
                    {
                        g.DrawString("=", lb.Font, brush, x, 0);
                        x += (g.MeasureString(",", lb.Font)).Width;
                    }
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 2020-09-05
      • 2017-04-27
      • 2012-12-01
      相关资源
      最近更新 更多