首先新建一个用户控件,在用户控件上添加五个PictureBox用来显示图片,然后给PictureBox控件导入两张图片(一张是选中的星星图片,一张未选中的星星图片)
五个控件的点击事件都添加同一个事件PictureBoxObj,具体用户控件的代码如下
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 WindowsFormsApplication1
{
public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}
private int _getGradeNum = 0;
/// <summary>
/// 获取星星数
/// </summary>
public int getGradeNum
{
get { return _getGradeNum; }
set { _getGradeNum = value; }
}
private int _setGradeNum;
/// <summary>
/// 设置星星数
/// </summary>
public int setGradeNum
{
get { return _setGradeNum; }
set { _setGradeNum = value; }
}
/// <summary>
/// 五个PictureBox通用点击事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void PictureBoxObj(object sender, EventArgs e)
{
foreach (Control var in this.Controls)
{
if (var is PictureBox)//所有pictureBox还原
{
PictureBox pic = var as PictureBox;
pic.Image = global::WindowsFormsApplication1.Properties.Resources.xx_f;//原始图片
}
}
System.Windows.Forms.PictureBox picObj = sender as System.Windows.Forms.PictureBox;//得到点击的PictureBox
int i = 0;
foreach (Control var in this.Controls)
{
if (var is PictureBox)
{
PictureBox pic = var as PictureBox;
pic.Image = global::WindowsFormsApplication1.Properties.Resources.xx_t;//选中后的图片
i++;
if (pic == picObj)//遍历到点击的pictureBox的时候结束
{
break;
}
}
}
getGradeNum = i;
}
/// <summary>
/// 星星等级绑定
/// </summary>
public void GradeBind()
{
for (int j = 0; j < this.Controls.Count; j++)
{
if (setGradeNum == j)
break;
Control var = this.Controls[j];
if (var is PictureBox)
{
PictureBox pic = var as PictureBox;
pic.Image = global::WindowsFormsApplication1.Properties.Resources.xx_t;
}
}
getGradeNum = setGradeNum;
}
}
}
然后新建一个winform窗体,在工具箱拖动用户控件到窗体上,如果工具箱没有,重新生成一次解决方案就可以看见了,如图所示
窗体内可以获取选中的星星数,也可以设置默认选中的星星数代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
userControl11.setGradeNum = 4;//设置星星数
userControl11.GradeBind();
}
private void button1_Click(object sender, EventArgs e)
{
///获取星星数
MessageBox.Show(userControl11.getGradeNum.ToString());
}
}
}
这样就大功告成了,看看效果图
当然还有很多可以优化改进的地方,比如可以做成积分等级,根据积分显示不同等级,仿QQ等级,当然代码需要做些修改,或者还有什么其他的地方可以用,或者有什么其他的好的想法,欢迎大家留言,一起进步!