如何使用c#从另一个usercontrol中调用usercontrol中的方法?

时间:2017-03-12 11:11:51

标签: c# c#-4.0

我有两个用户控件:UserControl1UserControl2UserControl1Update()方法。

我需要在调用UserControl2 UserControl1方法中致电Update()。它可以吗?

3 个答案:

答案 0 :(得分:1)

您也可以使用System.Action,即使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();
        }
    }

答案 1 :(得分:0)

如果要使用Usercontrol的对象访问方法,则必须像这样注册

UserControl1 uc1 = new UserControl1();
uc1.Update();

答案 2 :(得分:0)

您需要将第一个用户控件的实例传递给第二个:

UserControl1 uc1 = new UserControl1();
UserControl2 uc2 = new UserControl2(uc1);

....
    //在构造函数中将uc1对象设置为uc2中的私有成员变量,然后是..

//With the object of uc1 in uc2, update it
uc1.Update();