功能
Label绑定一个Value值,当Value值变化时自动切换文本内容和文本颜色。
例
Value=0时,Text=“绿灯”,ForeColor=Color.Green;Value=1时,Text=“红灯”,ForeColor=Color.Red;Value=2时,Text=“黄灯”,ForeColor=Color.Yellow;…
在集合编辑器配置要显示的文本和文本颜色。
代码
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace ChipsControls.UserControls
{
public partial class HsToggleLabel : Label
{
public HsToggleLabel()
{
InitializeComponent();
_value = 0;
this.Font = new Font("微软雅黑", 12f);
this.TextAlign = ContentAlignment.MiddleCenter;
UpdateLabel();
}
#region 新增属性
private int _value;
[Category("自定义"), Description("变量值"), Browsable(true)]
public int Value
{
get { return _value; }
set
{
_value = value;
UpdateLabel();
}
}
private List<DataAttribute> mDataAttribute = new List<DataAttribute>();
[TypeConverter(typeof(System.ComponentModel.CollectionConverter))]//指定类型装换器
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Category("自定义"), Description("文本和颜色")]
public List<DataAttribute> TextAndColor
{
get { return mDataAttribute; }
set { mDataAttribute = value; }
}
public class DataAttribute
{
[Description("文本"), Browsable(true)]
public string labelText { get; set; }
[Description("文本颜色"), Browsable(true)]
public Color labelColor { get; set; }
public DataAttribute()
{
}
public DataAttribute(string text,Color foreColor)
{
labelText = text;
labelColor = foreColor;
}
}
#endregion
#region 新增方法
private void UpdateLabel()
{
if (_value >= 0 && _value < mDataAttribute.Count)
{
Text = mDataAttribute[_value].labelText;
ForeColor = mDataAttribute[_value].labelColor;
}
else
{
Text = "null";//默认显示的文本
ForeColor = Color.Black;
}
}
#endregion
#region 重写方法
private void ToggleLabel_Paint(object sender, PaintEventArgs e)
{
UpdateLabel();
}
#endregion
}
}