0

当我启动这个程序时,我只进入 MessageBox http://www.google.com,但我应该得到http://www.yahoo.com,然后是http://www.google.com。那么,问题出在哪里?那么,你能帮我解决这个问题吗?谢谢 :)

有一个 XAML 代码:

<Window x:Class="WpfApplication19.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="800" Width="800">
<Grid Name="grid">
    <Button Name="btn" Content="Navigate" HorizontalAlignment="Left" Margin="697,223,0,0" VerticalAlignment="Top" Width="75" Click="button_Click"/>
    <Button Name="shower" Content="getValues" HorizontalAlignment="Left" Margin="697,262,0,0" VerticalAlignment="Top" Width="75" Click="shower_Click"/>
</Grid></Window>

并且有 C# 短代码:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using mshtml;

namespace WpfApplication19
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private List<string> list = new List<string>();
        private List<string> arrOfAdresses = new List<string>();
        private WebBrowser thisIsWeb;
        public MainWindow()
        {
            InitializeComponent();
            list.Add("http://www.yahoo.com");
            list.Add("http://www.google.com");
            thisIsWeb = new WebBrowser();
            thisIsWeb.Width = thisIsWeb.Height = 400;
            this.grid.Children.Add(thisIsWeb);
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            foreach (string s in list)
            {
                thisIsWeb.Navigate(s);
                thisIsWeb.LoadCompleted += OnthisIsWebCompleted;
            }
        }

        private void OnthisIsWebCompleted(object sender, NavigationEventArgs e)
        {
            WebBrowser bro = sender as WebBrowser;
            this.arrOfAdresses.Add(bro.Source.ToString());
        }

        private void shower_Click(object sender, RoutedEventArgs e)
        {
            foreach (string s in arrOfAdresses)
                MessageBox.Show(s);
        }
    }
}
4

1 回答 1

2

Well simple:

You are using the LoadCompleted to populate arrOfAdresses. Calling navigate does not guarantee LoadCompleted to be called! LoadCompleted is called - as the name suggests - as soon as the page you navigated to is loaded.

Since you navigate to two different urls immediately after each other, only the last call to Navigate will actually cause a website to be loaded - the prior navigations are implicitly "aborted" by the next call to Navigate.

So the only website that is loaded successfully (and therefore raises LoadCompleted) is http://www.google.com.

于 2013-09-20T14:45:37.947 回答