winform用户控件:文本切换label

这篇文章介绍了如何使用C#和WindowsForms开发一个名为HsToggleLabel的控件,它根据Value属性的变化动态改变文本内容和文本颜色,通过自定义属性DataAttribute进行配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

功能

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
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值