2010-05-14 1 views
1

나는 내가 내 주요 프로젝트 (메뉴 제어)시작 사용자 컨트롤을 동적

사용자 제어 프로젝트에 탭 컨트롤에 다른 프로젝트에서 사용자 컨트롤을로드하고자하는 사용자 정의 내장 된 메뉴 시스템을 가지고 : 는 foobar 메뉴 시스템 프로젝트 : 메뉴

탭 컨트롤에로드 할 수있는 기능 :

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이 null이라는 오류를 표시합니다. 올바른 매개 변수를 보내는 경우 사용자 정의 컨트롤을로드하는 방법과 궁금한 점을 혼동합니다.

답변

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; 
     }