2015-06-14 121 views
1

我有一個用戶控件,它包含一個組合框和一個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類中創建了一個屬性來傳遞必要的數據,但沒有運氣。

回答

0

您通過將其作爲一個參數的構造暴露的形式Class1

class Class1 
{ 
    private readonly UserControl _userControl; 

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

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

感謝名單的人讚賞 – Nash009

+0

這是使它工作的解決方案 – Nash009