WebBrowser
Many interfaces are implemented with websites. In a WPF program, we provide access to websites (and other data sources) with the WebBrowser
control.
Please first drag a WebBrowser
control from the Toolbox to your WPF window. You will want to expand the WebBrowser
to fit the window.
Loaded
Please next add a Loaded
attribute to your Window element. In the Window_Loaded
method, we access the WebBrowser
(with the name "MainBrowser
") and call Navigate on it.
WebBrowser
element. This WPF attribute will be automatically turned into a property in the C# code.<Window x:Class="WpfApplication28.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"> <Grid> <WebBrowser HorizontalAlignment="Left" Height="299" Margin="10,10,0,0" VerticalAlignment="Top" Width="497" Name="MainBrowser"/> </Grid> </Window>using System.Windows; namespace WpfApplication28 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { // ... Load this site. this.MainBrowser.Navigate("http://en.wikipedia.org/"); } } }
The WebBrowser
can access the network to download a web page. But it can also directly open a file on your local computer. This is done also with the Navigate method.
<h1>Hi there!</h2> <p> file.html </p>using System.Windows; namespace WpfApplication28 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { // ... Load a local HTML page. this.MainBrowser.Navigate("file:///C:/folder/file.html"); } } }
GoBack
, GoForward
The WebBrowser
control allows navigation with the GoBack
and GoForward
methods. They will throw exceptions if no pages are available for navigation.
CanGoBack
and CanGoForward
properties before calling GoBack
and GoForward
. This will eliminate exceptions.A WebBrowser
control can be used to load a web page. After loading, navigation can occur with GoBack
and GoForward
. We also used WebBrowser
to load an HTML file from the local disk.