0、前言
课题需要用到一个表示故障严重程度的控件,如下面几个图所示,分别可以表示低级、中级、高级等。这个控件可以看成颜色变化和进度条的组合。下面简单记录一下实现过程。
1、窗体控件库的建立
1.1、创建窗体控件库新项目,项目名称为riskLevel。
1.2、调整整体布局大小,更改名称(这个名称就是将来工具箱里控件的名称)
1.3、思路及其代码实现
要想实现风险提示的功能,首先需要输入两个变量:一个表示最大风险程度,一个表示当前风险程度,然后根据这两个变量进行颜色和进度调的控制即可。在这里,我们不需要使用任何的现有控件,只需要改变背景颜色即可。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace riskLevel
{
public partial class riskLevelControl: UserControl
{
private int value;
private int maximum;
public riskLevelControl()
{
InitializeComponent();
this.SetStyle(ControlStyles.UserPaint, true);使用自定义的绘制方式
this.Maximum = 3;//设置初始值
}
protected override void OnPaint(PaintEventArgs pe)
{
if (this.maximum == 2)
{
switch (this.value)
{
case 0:
this.ForeColor = Color.Green;
break;
case 1:
this.ForeColor = Color.Red;
break;
default:
this.ForeColor = Color.Red;
break;
}
}
else if (this.maximum == 3)
{
switch (this.value)
{
case 0:
this.ForeColor = Color.Green;
break;
case 1:
this.ForeColor = Color.Yellow;
break;
case 2:
this.ForeColor = Color.Red;
break;
default:
this.ForeColor = Color.Red;
break;
}
}
else if (this.maximum == 4)
{
switch (this.value)
{
case 0:
this.ForeColor = Color.Green;
break;
case 1:
this.ForeColor = Color.Violet;
break;
case 2:
this.ForeColor = Color.Yellow;
break;
case 3:
this.ForeColor = Color.Red;
break;
default:
this.ForeColor = Color.Red;
break;
}
}
var width = (this.Value + 1) * this.Width / this.Maximum;
pe.Graphics.FillRectangle(new SolidBrush(this.ForeColor), 0, 0, width, this.Height);
base.OnPaint(pe);
}
[Browsable(true)]
[Description("风险程度分级,支持2,3,4"), Category("自定义属性")]
public int Maximum
{
get { return maximum; }
set
{
if (value >= 4)
this.maximum = 4;
else
this.maximum = value;
//设置了最大值之后还要检查当前值是否符合要求
if (this.value >= this.maximum - 1)
this.value = this.maximum - 1;
this.Invalidate();
}
}
[Description("当前风险程度(从0开始,0代表第一级,1代表第二级别.....),"), Category("自定义属性")]
public int Value
{
get { return value; }
set
{
if (value >= this.maximum - 1)
this.value = this.maximum - 1;
else
this.value = value;
this.Invalidate();
}
}
}
}
1.4、控件调试
按F5启动调试,弹出如下窗体,同时生成控件文件(到该项目文件目录下的bin->debug中可找到)
我们更改两个自定义属性的值,测试能否满足预定需要即可。
3、控件使用
3.1、新建窗体应用项目
3.2、将生成的控件添加到工具栏
3.3、将控件拖动到主窗体
在主窗体载入事件添加测试代码:
private void Form1_Load(object sender, EventArgs e)
{
riskLevelControl1.Maximum = 3;
riskLevelControl1.Value = 1;
}
附完成工程: