UserControl控件调用主窗口方法
1、uc部分需要被主窗口访问的属性和方法需要定义出来
2、方法调用基于委托,这里有输入参数(string)和返回值(int),使用Func<string,int>,uc内部代码直接使用AutoIncr
3、主窗口创建uc时注册具体方法(AutoCount)到委托(Func)
private void Form3_Load(object sender, EventArgs e) //MainForm
{
Color[] c = { Color.AliceBlue,Color.Aqua,Color.Bisque,Color.Aquamarine,Color.Brown };
for (int i = 1; i < 21; i++)
{
UserControl1 uc = new UserControl1(i);
uc.BorderStyle = BorderStyle.FixedSingle;
uc.Padding = new Padding(2);
uc.BackColor = c[i % c.Length];
uc.AutoIncr += AutoCount;
flowLayoutPanel1.Controls.Add(uc);
}
}
public int AutoCount(string pid)
{
if (count.Keys.Contains(pid))
{
count[pid] = count[pid] + 1;
}
else
{
count.Add(pid, 1);
}
return count[pid];
}
}
public partial class UserControl1 : UserControl //自定义控件
{
public int pid { get; set; }
public SerialPort serialport { get; set; }
public string sn { get { return txt_sn.Text; } }
public string txt2 { get { return textBox2.Text; }}
public event Func<string, int> AutoIncr;
public UserControl1(int id)
{
InitializeComponent();
try
{
this.pid = id;
lbl_idx.Text = "P" + id.ToString();
serialport = new SerialPort("COM" + pid.ToString());
serialport.Open();
serialport.DataReceived += Serialport_DataReceived;
lbl_msg.Text = serialport.PortName + "Ready";
}
catch (Exception ex)
{
lbl_msg.Text = ex.Message;
txt_sn.Enabled = false;
textBox2.Enabled = false;
}
}
private void Serialport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = sender as SerialPort;
string content = sp.ReadExisting();
txt_sn.Text = content;
prosn();
}
public void prosn()
{
string sn = txt_sn.Text;
if (string.IsNullOrEmpty(sn))
{
lbl_msg.Text = "不能为空";
return;
}
int r = AutoIncr("P" + pid.ToString());
lbl_count.Text = r.ToString();
txt_sn.Text = "";
}
}