简体   繁体   English

从其他类访问UserControl方法和属性

[英]Accessing UserControl Methods and properties from other Class

What i have is a user control which contains a combobox and a DataGrid , what am trying to do is Accessing the UserContorl Methods from within my other Class which is named Class1 , in the class 1 i have some methods which will take advantage of the method in the UserControl(since the user control contains necessary data like combobox.tex) 我所拥有的是一个用户控件,其中包含一个组合框和一个DataGrid,我想要做的是从我名为Class1的其他类中访问UserContorl方法,在类1中,我有一些方法可以利用该方法在UserControl中(因为用户控件包含必要的数据,例如combobox.tex)

//The user control Code

    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
          InitializeComponent();

         }
       public string Mymethod()
       {
       return Combobox.Text ;
       }
    }

// The other class is 
class Class1
{
//Here i want to access the method from the withen of the userControl Class
UserControl1 cnt= new UserControl1()
//Also tried var cnt= new UserControl1()
Cnt.MyMethod()

}

What i have been trying is to create an instance of UserContorl in Class1 but i get no result since it is a new instance . 我一直在尝试在Class1中创建UserContorl的实例,但是由于它是一个新实例,所以没有任何结果。 Even at some point i have created a property inside the UserControl Class to pass up neccesary data but no luck as well . 甚至在某个时候,我还在UserControl类中创建了一个属性来传递必需的数据,但也没有运气。

You expose the form to Class1 by passing it as a parameter to the constructor: 通过将形式作为参数传递给构造函数,将形式公开给Class1

class Class1
{
    private readonly UserControl _userControl;

    public Class1(UserControl userControl)
    {
        _userControl = userControl;
    }

    public void SomeMethod()
    {
        _userControl.MyMethod() etc
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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