2012-09-18 25 views
2

問題是:當我刪除第一個消息框行時,我的程序不運行並在if語句行中拋出「異常已被調用的目標拋出」。但是,當我離開郵箱時,它運行良好。有人可以向我解釋爲什麼會發生這種情況,我能做些什麼來解決它?順便說一句,我對WPF相當陌生,任何幫助將不勝感激。WPF程序拋出無法解釋的調用異常

public BrowserMode() { 

     InitializeComponent(); 

     MessageBox.Show("Entering Browser Mode"); 
     if (webBrowser1.Source.Scheme == "http") 
     { 
      //cancel navigation 
      //this.NavigationService.Navigating += new NavigatingCancelEventHandler(Cancel_Navigation); 

      qd = new QuestionData(); 

      // code where stuff happens 
      var url = webBrowser1.Source; 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 

      // from h.RequestUri = "webcam://submit?question_id=45" 
      var parseUrl = request.RequestUri; //the uri that responded to the request. 
      MessageBox.Show("The requested URI is: " + parseUrl); 
+3

你有沒有抓到TargetInvocationException,看着的InnerException?看看http://stackoverflow.com/questions/2658908/why-is-targetinvocationexception-treated-as-uncaught-by-the-ide尋求幫助。 – user7116

+0

好吧,我註釋了MessageBox.show(「輸入瀏覽器模式)代碼,並通過try/catch塊包圍了代碼塊。消息說:」對象引用未設置爲對象的實例「爲什麼? – Sixers17

+1

'webBrowser1.Source'可能是'null'。無論如何,你應該把它移到'Loading',我會給出一個答案建議。 – user7116

回答

2

這種工作不適合構造,應搬出後才WebBrowser滿載。你有兩種選擇:

  1. Control.Loaded並在那裏執行此行爲。

    public BrowserMode() 
    { 
        InitializeComponent(); 
    
        this.Loaded += BroswerMode_Loaded; 
    } 
    
    void BrowserMode_Loaded(object sender, EventArgs e) 
    { 
        if (webBrowser1.Source != null 
        && webBrowser1.Source.Scheme == "http") 
        { 
         qd = new QuestionData(); 
         // ... 
        } 
    } 
    
  2. WebBrowser.Navigating並在那裏執行此行爲。

    public BrowserMode() 
    { 
        InitializeComponent(); 
    
        this.webBrowser1.Navigating += WebBrowser_Navigating; 
    }  
    
    void WebBrowser_Navigating(object sender, NavigatingCancelEventArgs e) 
    { 
        if (e.Uri.Scheme == "http") 
        { 
         qd = new QuestionData(); 
         // ... 
        } 
    } 
    
+0

嗨。我做了加載的方法,並且沒有拋出異常的異常但它仍然說源是空的,不會進入代碼塊。我試着明確地設置源屬性爲一個uri,但沒有奏效。我假設它爲空,因爲頁面沒有加載,但是,什麼是工作如果我在.xaml頁面中設置源代碼,這是否與此相關? – Sixers17

相關問題