从列表中导航WebBrowser

时间:2013-09-20 14:38:37

标签: c# wpf xaml

当我启动此程序时,我只进入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);
        }
    }
}

1 个答案:

答案 0 :(得分:2)

很简单:

您正在使用LoadCompleted填充arrOfAdresses。调用导航可以保证LoadCompleted被调用!一旦您导航到的页面被加载,就会调用LoadCompleted - 顾名思义。

由于您导航到两个不同的网址紧接着,只有最后Navigate的调用才会实际导致网站加载 - 导航会被下一次调用Navigate隐式“中止”。

因此,唯一成功加载的网站(因此会引发LoadCompleted)是http://www.google.com