![](/img/trans.png)
[英]How can i call method from UserControl to another UserControl or another aspx.Page using Events?
[英]How can i call method from usercontrol from another usercontrol using c#?
我有兩個用戶控件: UserControl1
和UserControl2
。 UserControl1
有一個Update()
方法。
我需要調用UserControl2
在調用UserControl1
Update()
method.How可以嗎?
您也可以像這樣使用System.Action
,甚至將UserControleOne
的參數UserControleOne
可選。
class UserControlOne
{
public void Update(Action updateAction = null)
{
updateAction?.Invoke(); # you could also write updateAction();
}
}
class UserControlTwo
{
public void Update()
{
Console.WriteLine("Updated");
Console.ReadKey();
}
}
class Program
{
static void Main(String[] args)
{
// calling exmaple 1
UserControlOne uc = new UserControlOne();
UserControlTwo uc2 = new UserControlTwo();
uc.Update(uc2.Update);
// calling example 2
UserControlOne anotherUserControl = new UserControlOne();
anotherUserControl.Update();
}
}
如果要使用Usercontrol對象訪問方法,則必須這樣注冊
UserControl1 uc1 = new UserControl1();
uc1.Update();
您需要將第一個用戶控件的實例傳遞給第二個:
UserControl1 uc1 = new UserControl1();
UserControl2 uc2 = new UserControl2(uc1);
....
//然后將uc1對象設置為uc2中構造函數中的私有成員變量。
//With the object of uc1 in uc2, update it
uc1.Update();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.