从其他类访问UserControl方法和属性
问题描述:
我有一个用户控件,它包含一个组合框和一个DataGrid,我试图做的是从我的另一个类Class1中,在类1中访问UserContorl方法我有一些方法,将利用该方法在用户控件(因为用户控件包含像combobox.tex必要的数据)从其他类访问UserControl方法和属性
//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()
}
我一直试图在Class1的,但我创造UserContorl的实例因为它是一个新实例,所以没有结果。即使在某些时候,我已经在UserControl类中创建了一个属性来传递必要的数据,但没有运气。
答
您通过将其作为一个参数的构造暴露的形式Class1
:
class Class1
{
private readonly UserControl _userControl;
public Class1(UserControl userControl)
{
_userControl = userControl;
}
public void SomeMethod()
{
_userControl.MyMethod() etc
}
}
感谢名单的人赞赏 – Nash009
这是使它工作的解决方案 – Nash009