2

问题是:当我删除第一个消息框行时,我的程序没有运行并在 if 语句行上抛出“异常已被调用的目标抛出”。但是,当我将消息框留在那里时,它运行良好。有人可以向我解释为什么会发生这种情况以及我可以做些什么来解决它?顺便说一句,我对 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);
4

1 回答 1

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();
            // ...
        }
    }
    
于 2012-09-18T21:27:42.323 回答