简体   繁体   中英

How can i call method from usercontrol from another usercontrol using c#?

I have two usercontrols: UserControl1 and UserControl2 . UserControl1 have a Update() method.

I need call UserControl2 in the call UserControl1 Update() method.How can it?

You could also use System.Action like so even making the parameter of UserControleOne optional.

    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();
        }
    }

If you want to access method using object of Usercontrol, you have to register it like this

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

You need to pass the instance of the first User Control into the second:

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

....
// Set the uc1 object to a private member variable in uc2 in the constructor, then..

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM