我有一个带有计时器的用户控件
public partial class Cumle : UserControl
{
private bool cond=false;
//Some Code....
private void timer2_Tick(object sender, EventArgs e)
{
//Some Code....
if(//some condition...)
cond=true;
}
}
我正在使用Windows窗体。我想显示一个消息框,告诉我cond是真的。我想在不使用表单上的计时器的情况下制作这些东西。
public partial class Form1 : Form
{
//What I must write here?
}
答案 0 :(得分:1)
如上所述,您应该使用事件。我会这样:
public partial class Cumle : UserControl
{
public event EventHandler ConditionChangedToTrue;
protected virtual void OnConditionChangedToTrue(EventArgs e)
{
if (ConditionChangedToTrue != null)
ConditionChangedToTrue(this, e != null ? e : EventArgs.Empty);
}
private void timer2_Tick(object sender, EventArgs e)
{
//Some Code....
if (true) // add your condition
{
cond = true;
OnConditionChangedToTrue(null);
}
}
}
public partial class Form1 : Form
{
private Cumle cumle = new Cumle();
public Form1()
{
InitializeComponent();
cumle.ConditionChangedToTrue+= Cumle_ConditionChangedToTrue;
}
private void Cumle_ConditionChangedToTrue(object sender, EventArgs e)
{
// add your event handling code here
throw new NotImplementedException();
}
}
答案 1 :(得分:0)
您需要向UserControl添加公共事件,并从主表单订阅它。
这样的事情应该这样做:
public partial class Cumle : UserControl
{
public event Action<bool> ConditionChanged = delegate {};
private bool cond=false;
//Some Code....
private void timer2_Tick(object sender, EventArgs e)
{
//Some Code....
if(//some condition...)
{
cond=true;
ConditionChanged(cond);
}
}
}
然后以你的形式:
public partial class Form1 : Form
{
void SubscribeToConditionChanged()
{
myUserControl.ConditionChanged += ShowDlg;
}
void ShowDlg(bool condition)
{
MessageBox.Show("....");
}
}