[英]Calling a method in a UserControl from another UserControl
我已经研究这个问题一段时间了,我似乎找不到有效的解决方案。 我想从另一个 UserControl 中的方法调用一个方法 UserControl。
在 UserControl1 我有一个方法:
public void update(int lineNum, double price)
{
// do stuff...
// then call the method in another UserControl
UserControl2 uc2 = new UserControl2();
uc2.refreshList();
}
在 UserControl2 中,我有一个方法:
public void refreshList()
{
// do stuff....
}
当然,除了简单地创建 UserControl 的 object 并以这种方式调用该方法之外,我还尝试了其他方法,但似乎没有任何效果。
在用户控件之间存在这样的依赖关系是不好的:它限制了使用并且使得它们很难单独测试。
您有多种选择来实现您想要的。
让调用者进行编排
您没有调用update
的代码所在的 state 。 但由于该方法是public
,我假设这是从UserControl1
外部调用的。 也许可以在调用userControl1.update()
之后将userControl2.refreshList()
调用放在那里
使用事件
您可以在UserControl1
中定义一个事件,例如public event EventHandler UpdatePerformed
并在update
方法结束时引发它。 然后在您的表单中,订阅此事件并从那里调用refreshList
:
userControl1.UpdatePerformed += (s, e) => userControl2.refreshList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.