【发布时间】:2017-02-09 08:01:32
【问题描述】:
label1 text&property 和 label2 text&property 可以合二为一,在label3中显示并添加文字=吗?因为我现在使用的是label1 和label2 并排使用。
告诉我是否有其他方法
Ps:我在 red 或 blue 等数据库中定义颜色。
【问题讨论】:
-
当你说组合属性时......哪些?
label1 text&property 和 label2 text&property 可以合二为一,在label3中显示并添加文字=吗?因为我现在使用的是label1 和label2 并排使用。
告诉我是否有其他方法
Ps:我在 red 或 blue 等数据库中定义颜色。
【问题讨论】:
您可以像这样组合文本内容:
label3.Text = label1.Text + " = " + label2.Text;
但是你会失去不同的颜色。不幸的是,这是不可能的。更多详情请查看this answer
【讨论】:
使用 string.format 将 2 个标签文本组合在一起。
label3.Text = string.Format("{0}={1}", label1.Text, label2.Text);
【讨论】:
为什么要投反对票¿
您可以将自己的文本图像写入您的标签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;
}
}
}
}
【讨论】: