word中的加粗变斜之类的一直让我以为是button,直到我接触了自定义控件,才发现实现这种机能最好的是CheckBox,然后我们在做一个系统的时候,这种控件有可能要用好多次,总不能在用一次的时候,就去拉一个CheckBox,并进行各种复制吧,所以最好的方式就是自定义一个控件,自定义点击的Image属性,这样你只要替换掉Image,你就要让这个变成变粗的CheckBox,变斜的CheckBox等等。

  private void CmpCheckButton_MouseLeave(object sender, EventArgs e)
        {
            if (!this.Checked)
            {
                this.BackgroundImage = ImageNormal;
                this.Invalidate();
            }
        }
        private void CmpCheckButton_MouseHover(object sender, EventArgs e)
        {
            if (!this.Checked)
            {
                this.BackgroundImage = ImageMouseEnter;
                this.Invalidate();
            }
        }
        private void CmpCheckButton_CheckedChanged(object sender, EventArgs e)
        {
            var image = ImageNormal;
            if (this.Checked && ImageChecked != null)
            {
                image = ImageChecked;
            }
            else
            {
                image = ImageMouseEnter;
            }
            this.BackgroundImage = image;
            this.Invalidate();
        }
        private System.Drawing.Image _imageNormal;
        [Description("通常图片")]
        public System.Drawing.Image ImageNormal
        {
            get { return _imageNormal; }
            set
            {
                _imageNormal = value;
                this.BackgroundImage = _imageNormal;
                this.Invalidate();
            }
        }
        private System.Drawing.Image _imageChecked;
        [DefaultValue(null), Description("Checked状态图片")]
        public System.Drawing.Image ImageChecked
        {
            get { return _imageChecked; }
            set
            {
                _imageChecked = value;
                if (Checked) this.BackgroundImage = _imageChecked;
                this.Invalidate();
            }
        }
        private System.Drawing.Image _imageMouseEnter;
        [DefaultValue(null), Description("MouseEnter状态图片")]
        public System.Drawing.Image ImageMouseEnter
        {
            get { return _imageMouseEnter; }
            set
            {
                _imageMouseEnter = value;
                this.BackgroundImage = value;
                this.Invalidate();
            }
        }

C# windform自定义控件的属性小知识-LMLPHPC# windform自定义控件的属性小知识-LMLPHP

05-26 12:34