2014-12-04 101 views
0

我有幾個子窗體,但他們有一個共同的方法,get_CurrentClamp()。我想從MDI父級調用當前活動mdichild的方法。我如何從mdi父c調用子窗體的方法#

這是一個菜單項中的MdiParent形式onclick事件MDIMain.cs應該調用該方法。

.... 
private void mnugetCToolStripMenuItem_Click(object sender, EventArgs e) 
    { 
    if (MdiChildren.Any()) 
      { 
       Form f = this.ActiveMdiChild;    
       f.get_CurrentClamp(varCurrentThreshhold); 
      } 
    } 
..... 

在子窗體frmDashboard.cs

public void get_CurrentClamp(float curThreshhold=5.5) 
     { 
      ... 
     } 

,但我不斷收到錯誤,任何地方我的問題呢?任何幫助將不勝感激!

該錯誤的越來越是這樣

錯誤3「System.Windows.Forms.Form中」不包含 「get_CurrentClamp」的定義和沒有擴展方法「get_CurrentClamp」 接受的第一個參數類型「System.Windows.Forms.Form中」可能 找到(是否缺少using指令或程序集引用?)

那是錯誤上午的MdiParent形式獲得。

+1

什麼是錯誤? – 2014-12-04 06:40:14

+0

你沒有找到get_CurrentClamp? – 2014-12-04 06:42:15

+5

您正在轉換爲標準的Form類型,這當然沒有名爲get_CurrentClamp()的方法。您可以使用Reflection來獲取方法並調用它。更好的解決方案是讓所有的子表單都實現一個包含該方法的**接口**;那麼你可以投到界面並調用方法... – 2014-12-04 07:05:11

回答

0

感謝Idle_Mind我通過使用接口解決了這個問題。 我在一個叫IChildMethods.cs及以下文件中創建一個新的界面接口

internal interface IChildMethods 
    { 
     void get_CurrentClamp(float curThreshhold=5.5); 
    } 

及子窗體,我只是包括在形式frmDashboard.cs像下面的界面;

public partial class frmDashboard : Form, IChildMethods 

,並在mdi窗體MDIMain.cs

.... 
private void mnugetCToolStripMenuItem_Click(object sender, EventArgs e) 
    { 
    if (MdiChildren.Any()) 
      { 
       if (this.ActiveMdiChild is IChildMethods) 
      { 
       ((IChildMethods)this.ActiveMdiChild).get_CurrentClamp(varCurrentThreshhold); 
      }    

      } 
    } 
..... 

我還沒有使用反射的方法,因爲接口方法有效嘗試,但我只是想知道,反思是不是使用的界面更好在這樣的問題中

0

如果你確定活動形式將是實例之一,你可以聲明F到是此類型:

frmDashboard f = this.ActiveMdiChild; 

你可能想以防萬一這周圍一個try/catch。 (在VB中工作,無論如何,不​​知道C#。)

相關問題