问题是:当我删除第一个消息框行时,我的程序没有运行并抛出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);
答案 0 :(得分:2)
这种工作不适合构造函数,应该在WebBrowser
完全加载之后移出。您有两种选择:
挂钩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();
// ...
}
}
挂钩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();
// ...
}
}