Logo
programming4us
programming4us
programming4us
programming4us
Home
programming4us
XP
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server
programming4us
Windows Phone
 
Windows Phone

Windows Phone 7 Programming Model : Web Browser Control

- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
4/5/2013 5:08:29 PM

The WebBrowser controlis not a task, but it is related to the web browser task, so it makes sense to cover it here. The WebBrowser control is much more programmable than the WebBrowserTask covered in the previous section on Launchers.

The WebBrowser control can be embedded within the XAML of an application, so the content appears more integrated with the application itself. It is still a full browser, so you can navigate away from content if following hyperlinks, but you can configure how it behaves. The following is a list of the WebBrowser control class members to help guide capabilities:

  • Base: Sets the base directory in isolated storage that is used to resolve relative URLs.

  • CacheMode: Determines whether content should be cached when possible.

  • InvokeScript: Executes a function in the script for the currently loaded content.

  • IsScriptEnabled: Set to true to enable scripting. Applies to the next document navigated to, not the current document.

  • LoadCompleted: Event fires when the content is fully loaded. Permits having a loading animation.

  • Navigate: Navigates the browser control to the provided URI. Two overloads with the second taking post data and additional headers.

  • Navigated: Fires after successful navigation.

  • Navigating: Fires when browser is navigating

  • NavigateToString: Allows loading the provided HTML string into the browser.

  • ScriptNotify: Fires when JavaScript calls window.external.Notify(<data>).


1. Basic WebBrowser Control Sample

In the BasicWebBrowserControlPage.xaml, there is a WebBrowser control, a TextBox to enter a URL, and a load button in the application bar. There is also a semi-transparent Rectangle to demonstrate transparency support in the WebBrowser control.

The project includes a simple animation named AnimateGreenRect that spins and animates the size of the green Rectangle while loading content into the WebBrowser control. The Storyboard object is built using Expression Blend. First a keyframe is added at 0 seconds with the configured position. The yellow timeline indicator is slid over to 500ms and another keyframe is added by clicking the small circle with a plus sign in the Object and Timeline window as shown in Figure 1.

Figure 1. Creating the animation

With the yellow timeline indicator over the second keyframe, move over to the Properties window and expand the Transform section. Select the Rotate tab and set the Angle property to 180 degrees. Next, select the Scale tab and set X and Y to .5. Click on the name of the Storyboard at the top of the Object and Timeline window to select the newly created Storyboard and move over to the Properties window. Check the AutoReverse checkbox and set the RepeateBehavior to Forever.

It takes just a little bit of code to wire-up playing the animation while loading the web page. Listing 1 has the code.

Example 1. BasicWebBrowserControlPage.xaml.cs Code File
public partial class BasicWebBrowserControlPage : PhoneApplicationPage
  {
    public BasicWebBrowserControlPage()
    {
      InitializeComponent();

webBrowserControl.LoadCompleted += new
       System.Windows.Navigation.LoadCompletedEventHandler(webBrowserControl_LoadCompleted);
      webBrowserControl.Navigating += new
       EventHandler<NavigatingEventArgs>(webBrowserControl_Navigating);
    }

    void webBrowserControl_Navigating(object sender, NavigatingEventArgs e)
    {
      System.Diagnostics.Debug.WriteLine(e.Uri);
    }

    private void loadUrlAppBarButton_Click(object sender, EventArgs e)
    {
      AnimateGreenRect.Begin();
      webBrowserControl.Navigate(new Uri(WebAddressTextBox.Text));
    }

    void webBrowserControl_LoadCompleted(object sender, System.Windows.Navigation
.NavigationEventArgs e) { AnimateGreenRect.Stop(); } }

You can hook into the various events available listed above in XAML as we have done previously. Using the += syntax, Visual Studio will automatically generate the correct event handler just by hitting the tab key to generate it:

webBrowserControl.Navigating += new
   EventHandler<NavigatingEventArgs>(webBrowserControl_Navigating);

An important capability of the WebBrowser control is to load HTML fragments using the WebBrowser.NavigateToString() method. Another important capability is the WebBrowser.Base property allows relative URLs for items such as images to be loaded locally. Caching items to the file system can save download time and bandwidth for the user, improving overall application performance. The next section covers interacting with the HTML content via scripting.

2. WebBrowser Control Scripting Sample

The WebBrowser control supports HTML, CSS, and JavaScript. To support JavaScript, set the IsScriptEnabled property to true in XAML or in the code-behind. The WebBrowserControlScriptingPage.xaml sample contains a WebBrowser control that is loaded with an HTML page stored in the xap as content. The HTML page contains two JavaScript script functions; one that sets the content on a DIV, the other script sets the source to an IMG tag in the HTML. Listing 2 has the HTML file that is stored in the xap as content.

Example 2. The content.html Code File
<html>
<head>
<title>Test Script</title>
<script type="text/javascript">

    function PassData(data) {

content1.innerHTML = data;
    }

    function SetImageSource(source) {
      image1.src = source;
    }
    <style type="text/css">
    body {
      font-family: "Segoe WP";
      font-size: medium;
      color: #FFFFFF;
      background-color: #000000;
    }
  </script>
</head>
<body>
  <h3>
    Page Loaded</h3>
  <img alt="image goes here" src="" id="image1" />
  <h4>
    Text appears below:</h4>
  <div id="content1">
  </div>
</body>
</html>

					  

The HTML file has a little bit of formatting to help the HTML file blend in with the UI. The style was creating using the Visual Studio Manage Styles dialog box by clicking the new style button. You can see the styling in the CSS style applied to the HTML BODY tag. The style does the following:

  • Sets the font to match the Windows Phone 7 font (Segoe WP)

  • Font Size to medi and a foreground color of White

  • Set the background color to Black

When using the WebBrowser control, try to have the content blend into the UI with styling. Windows Phone 7 supports two themes, light and dark, so you should dynamically apply styles based on the theming, which you will see is not difficult to do via the scripting bridge.

The WebBrowser Control supports invoking script. Listing 3 has the code-behind file where the Silverlight code calls the two scripts.

Example 3. The WebBrowserControlScriptingPage.xaml.cs Code File
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows;
using Microsoft.Phone.Controls;

namespace WebBrowserControl.pages
{
  public partial class WebBrowserControlScriptingPage : PhoneApplicationPage
  {

					  

public WebBrowserControlScriptingPage()
    {
      InitializeComponent();
      Loaded += new RoutedEventHandler(WebBrowserControlScriptingPage_Loaded);
    }

    void WebBrowserControlScriptingPage_Loaded(object sender, RoutedEventArgs e)
    {
      SetUpWebBrowserControlContent();
      webBrowserControl.Base = "home";
      webBrowserControl.Navigate(new Uri("content.html", UriKind.Relative));
    }

    private void SetUpWebBrowserControlContent()
    {
      //Copy content out of xap and into isolated storage
      using (IsolatedStorageFile isf =
              IsolatedStorageFile.GetUserStoreForApplication())
      {
        //if (!isf.DirectoryExists("home"))
        //{
        isf.CreateDirectory("home");
        //create base html file
        using (IsolatedStorageFileStream fs =
          isf.OpenFile("home/content.html", System.IO.FileMode.Create))
        {
          byte[] buffer = new byte[256];
          int count = 0;
          Stream resourceStream =
            Application.GetResourceStream(
                     new Uri("html/content.html", UriKind.Relative)).Stream;
          count = resourceStream.Read(buffer, 0, 256);
          while (count > 0)
          {
            fs.Write(buffer, 0, count);
            count = resourceStream.Read(buffer, 0, 256);
          }
        }
        //Create Image directory
        isf.CreateDirectory("home/images");
        //Create image file
        using (IsolatedStorageFileStream fs =
          isf.OpenFile("home/images/image.jpg", System.IO.FileMode.Create))
        {
          byte[] buffer = new byte[256];
          int count = 0;
          Stream resourceStream = Application.GetResourceStream(
            new Uri("images/image.jpg", UriKind.Relative)).Stream;
          count = resourceStream.Read(buffer, 0, 256);
          while (count > 0)
          {
            fs.Write(buffer, 0, count);
            count = resourceStream.Read(buffer, 0, 256);
          }
        }
      }
    }

					  

private void loadUrlAppBarButton_Click(object sender, EventArgs e)
    {
      //Invoke script
      webBrowserControl.InvokeScript(
            "PassData", "This is the data.  Hello from Silverlight.");
      webBrowserControl.InvokeScript(
            "SetImageSource", "images/image.jpg");
    }
  }
}

The InvokeScript method on the WebBrowser control takes the name of the JavaScript method and a string array for parameters. When the refresh button is clicked, the loadUrlAppBarButton_Click shown in Listing 3 event fires resulting in the UI shown in Figure 2.

Figure 2. WebBrowser control scripting page
Other -----------------
- Windows Phone 7 Programming Model : Tasks
- Windows Phone 7 Programming Model : Application Data Persistence
- Windows Phone 7 Programming Model : Device Information
- iphone Programming : Mixing OpenGL ES and UIKit, Rendering Confetti, Fireworks, and More: Point Sprites
- iphone Programming : Animation with Sprite Sheets, Image Composition and a Taste of Multitexturing
- XNA Game Studio 3.0 : Creating Game Components - Adding Game Sounds
- Iphone Application : Using Gesture Recognizers (part 4)
- Iphone Application : Using Gesture Recognizers (part 3)
- Iphone Application : Using Gesture Recognizers (part 2)
- Iphone Application : Using Gesture Recognizers (part 1)
 
 
Top 10
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
 
programming4us
Windows Vista
programming4us
Windows 7
programming4us
Windows Azure
programming4us
Windows Server