2010-05-14 47 views
1

我有一個定製的菜單系統中,我想從另一個項目加載用戶控件到選項卡控件上我的主項目(菜單控制)啓動用戶控制在一個標籤控件動態

用戶控制項目: foob​​ar的 菜單系統項目:菜單

將其裝入標籤控制功能:

private void LaunchWPFApplication(string header, string pPath) 
     { 
      // Header - What loads in the tabs header portion. 
      // pPath - Page where to send the user 

      //Create a new browser tab object 
      BrowserTab bt = tabMain.SelectedItem as BrowserTab; 
      bt = new BrowserTab(); 
      bt.txtHeader.Text = header; 
      bt.myParent = BrowserTabs; 

      //Load in the path 
     try 
     { 
      Type formType = Type.GetType(pPath, true); 
      bt.Content = (UserControl)Activator.CreateInstance(formType); 
     } 
     catch 
     { 
      MessageBox.Show("The specified user control : " + pPath + " cannot be found"); 
     } 

      //Add the browser tab and then focus    
      BrowserTabs.Add(bt); 
      bt.IsSelected = true; 
     } 

而且我發送到功能爲例什麼:

LaunchWPFApplication("Calculater", "foobar.AppCalculater"); 

但每次運行時,應用程序都會抱怨formType爲空。我很困惑如何加載用戶控件,並好奇我是否發送了正確的參數。

回答

1

我遇到的問題是調用Type.GetType。 MSDN給出的通用呼叫是

Type formType = Type.GetType("AppCalculater"); 

其中調用獲取指定名稱的類型。這仍然不管返回null。然後我添加了命名空間到混音。

Type formType = Type.GetType("foobar.AppCalculater"); 

但是,這仍然給我一個錯誤,調用foobar中的其他項目文件。爲了獲得其他項目中的用戶控件,我在控件和命名空間調用之後添加了程序集。

Type formType = Type.GetType("foobar.AppCalculater,foobar"); 

然後,我可以使用此調用動態地引用所有用戶控件。因此,我現在更新的調用來從另一個項目加載用戶控件到我的選項卡控件中,如下所示:

private void LaunchWPFApplication(string header, string pPath) 
     { 
      // Header - What loads in the tabs top portion. 
      // Path - Page where to send the user 

      //Create a new browser tab object 
      BrowserTab bt = tabMain.SelectedItem as BrowserTab; 
      bt = new BrowserTab(); 
      bt.txtHeader.Text = header; 
      bt.myParent = BrowserTabs; 

      //Load in the path 
      try 
      { 
       Type formType = Type.GetType(pPath); //Example "foobar.foobarUserControl,foobar" 
       bt.Content = Activator.CreateInstance(formType); 
      } 
      catch (ArgumentNullException) 
      { 
       MessageBox.Show("The specified user control : " + pPath + " cannot be found"); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("An error has occurred while loaded the specified user control : " + pPath + ". It includes the following message : \n" + ex); 
      } 
      //Add the browser tab and then focus  
      try 
      { 
       BrowserTabs.Add(bt); 
      } 
      catch(InvalidOperationException) 
      { 
       MessageBox.Show("Cannot add " + pPath + " into the tab control"); 
      } 
      bt.IsSelected = true; 
     }