Windows Phone Controls and Events

,Windows Phone Controls and Events

Web Browser, Own Work

"The Windows Phone SDK comes with a standard set of controls. The Windows Phone Toolkit provides additional controls to enhance the interface."

    Windows Phone Controls

  • The Windows Phone SDK comes with a standard set of controls from the System.Windows.Controls namespace which include:
    • Border - draws a border, background, or both around another object.
    • Button - draws a button control, which reacts to the ButtonBase.Click event.
    • CheckBox - draws a control that presents a binary choice (yes/no) between one of two mutually exclusive options.
    • RadioButton - draws a control that allows the user to choose only one from a predefined set of mutually exclusive options.
    • HyperlinkButton - draws a button control that displays a hyperlink.
    • ListBox - contains an open list of selectable items (Properties: SelectedIndex, Selected Item. Events: SectionChanged).
    • Image - displays an image in PNG or JPEG format.
    • Map - the Windows Phone version of the Bing Maps Silverlight Control is still supported but it is deprecated and should only be kept for an existing app that you have upgraded from Windows Phone OS 7.1 to Windows Phone 8. To add Bing Maps to a Windows Phone 7 or Windows Phone 8, you can use Bing Maps AJAX Control, Version 7.0 or the the Windows Phone 8 Maps API. The Windows Phone 8 Maps API does not use Bing Maps.
    • ProgressBar - shows the progress of an operation that has a known duration, or shows that an indeterminate operation is in progress.
    • MediaElement - a rectangular control that can contain audio and video as its content. See list of supported media formats. Note: Closed Captioning (subtitles) is supported thru the use of the TimeLineMarker object. (Properties: AutoPlay, CanPause, CanSeek, CurrentState, Duration, IsMuted, Volume, Balance, AudioStreamCount, AudioStreamIndex) Note: HTML5 VIDEO and AUDIO tags are now supported in all browsers and is an alternative to the Silverlight controls
    • TextBlock - display (only) of text. A lightweight control for small amounts of text.
    • TextBox - text input (single line or multi-line).
    • ToggleButton - base class for controls that can switch states, such as CheckBox and RadioButton
  • Additional Windows Phone controls are in the class library Microsoft.Phone.Controls which include:
    • LongListSelector - displays a list of selectable items with a mechanism for users to jump to a specific section of the list. (WP 8 Only)
    • Panorama - creates a panoramic view of items that can be panned side-to-side. (Can use project template: Windows Phone Panorama Application)
    • Pivot - provides a quick way to manage the navigation of views within an application. The control can be used as a navigation interface for filtering large sets or switching between views. Useful for show the same data in different ways, on different pages, to the user. (Can use project template: Windows Phone Pivot Application)
    • WebBrowser - allows HTML rendering and navigation functionality to be embedded in an application.
  • The Windows Phone Toolkit provides the additional controls:
    • AutoCompleteBox - provides a text box for user input and a drop-down that contains possible matches based on the input in the text box.
    • ContextMenu - provides a pop-up menu that enables a control to expose functionality that is specific to the context of the control.
    • CustomMessageBox - provides a customized version of MessageBox
    • DateTimePickers - provides a control that allows the user to select a date and a time and to display the date and time with a specified format.
    • ListPicker - (Combobox replacement) shows the selected item from a list and also allows the user to pick from a list if they want to change it.
    • LongListMultiSelector - Displays a list of selectable items with a mechanism for users to jump to a specific section of the list.
    • WrapPanel - positions child elements in sequential position from left to right, breaking content to the next line at the edge of the containing box. Subsequent ordering happens sequentially from top to bottom or from right to left, depending on the value of the Orientation property.

NuGet to Install Windows Phone Toolkit

,Windows Phone Toolkit

Windows Phone Toolkit, Fair Use

Adding Controls to an Application

"Dragging and dropping a control from the Visual Studio toolbox is an easy way to add controls to an application. However, some experienced developers prefer to code controls in the xaml code."

  • There are three ways to add a control to an application:
    1. Drag from the toolbox and drop on the design surface.
    2. Code the control in the XAML code.
    3. Code the control in the code-behind file (eg C# Code).
  • The appearance of controls are changed through their properties (width, height, color, etc.).
  • Controls have actions that can trigger events. Once a control has been added to an application, code is placed inside the event handlers to make the control perform the desired behavior.


Handling Events

"Event handlers can be assigned for UI elements in XAML, or in the code-behind files. For UI objects that are declared in XAML, event handler code must be defined in the partial class that serves as the code-behind for a XAML page."

  • Event handlers contain program logic that define the behaviors of controls. Event handlers can be created in different ways. Below are two ways to create an event handler:
    1. Create Event Handler for Default Event using Design Surface.
      • In the Visual Studio design surface, if you double-click on a control, VS will generate the connection for the control's default event. For example, if you double-click on a button, VS will:
        1. Add the default event (Click="button1_Click") to the xaml definition of the control:

                  <Button Name="button1"
                          Content="Button"
                          Height="23"
                          Width="75"               
                          VerticalAlignment="Top"               
                          Click="button1_Click" />

        2. Add the stub for the event handling method (button1_Click) in the code-behind file:

          span style=" font-size: 10pt; font-family: 'Consolas'; font-style: normal; font-weight: normal; color: #0000ff; background-color: transparent; text-decoration: none;">namespace Events
          {
              public partial class MainPage : UserControl
              {
                  public MainPage()
                  {
                      InitializeComponent();
                  }

                  private void button1_Click(object sender, RoutedEventArgs e)
                  {

                  }
              }
          }
    2. Create Event Handler in Code-behind File.
      • Another option for handling events is have the code-behind file handle everything. That is the event handler is not attached in the xaml, instead we attach the event handler in the code-behind (myBtn.Click += new RoutedEventHandler(myBtn_Click); Below is a coding example of this method.

                <Button Name="button1"
                        Content="Button"
                        Height="23"
                        Width="75"               
                        VerticalAlignment="Top" />

        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Net;
        using System.Windows;
        using System.Windows.Controls;
        using System.Windows.Documents;
        using System.Windows.Input;
        using System.Windows.Media;
        using System.Windows.Media.Animation;
        using System.Windows.Shapes;

        namespace Events
        {
            public partial class MainPage : UserControl
            {
                public MainPage()
                {
                    InitializeComponent();
                    button1.Click += new RoutedEventHandler(button1_Click);
                }

                private void button1_Click(object sender, RoutedEventArgs e)
                {
                
                }
            }
        }

,Event Routing

Event Routing, Fair Use

Handling Routed Events

"Routed events are events which navigate up (Bubbling) or down (Tunneling) the UI element hierarchy according to their routing strategy."

  • The event model for Silverlight supports navigating up the element hierarchy (bubbling events). Under this model a control can raise an event that will be handled by its parent control. This will continue up the control hierarchy until an event handler declares it has handled the event (e.Handled = true;). Note: Silverlight for Windows Phone does NOT support tunnel routing of events (ie. going down the hierarchy). Additionally Silverlight for Windows Phone does NOT support user-created bubbling events (new events you create will never bubble).

  • Not all events support routing. Below is a list of Silverlight's input events that support bubble routing:
    • KeyDown
    • KeyUp
    • GotFocus
    • LostFocus
    • MouseLeftButtonDown
    • MouseRightButtonDown
    • MouseLeftButtonUp
    • MouseRightButtonUp
    • MouseMove
    • MouseWheel
    • BindingValidationError
    • DragEnter
    • DragLeave
    • DragOver
    • Drop
  • Below is and example of how events can bubble up the control hierarchy. The MouseRightButtonDown event is handled by the nested controls (Rectange, StackPanel, Border, Grid) and since none of the events are coded to declare it has handled the event (e.Handled = true;) the event bubbles up to be handled by the topmost control (Grid=Layout Root).

    Event Bubbling (Right-Click on Different Colored Areas)
    Get Microsoft Silverlight

    MainPage.xaml

    <UserControl x:Class="Events.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        d:DesignHeight="213" d:DesignWidth="297">

        <Grid x:Name="LayoutRoot" Background="White"
              MouseRightButtonDown="LayoutRoot_MouseRightButtonDown"
              Height="131"
              Width="268">
            <Border x:Name="theBorder"
                    Background="Blue"
                    Margin="24,12,34,20"
                    MouseRightButtonDown="theBorder_MouseRightButtonDown">
                <StackPanel Background="Green"
                            x:Name="theStackPanel"
                            MouseRightButtonDown="theStackPanel_MouseRightButtonDown"
                            Height="69"
                            Width="157">
                    <Rectangle x:Name="theRectangle"
                               Fill="Red"
                               MouseRightButtonDown="theRectangle_MouseRightButtonDown"
                               Height="45"
                               Width="85"></Rectangle>
                </StackPanel>
            </Border>
        </Grid>
    </UserControl>


    MainPage.xaml.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Animation;
    using System.Windows.Shapes;

    namespace Events
    {
        public partial class MainPage : UserControl
        {
            private string message = "";
            public MainPage()
            {
                InitializeComponent();
            }

            private void LayoutRoot_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
            {
                message += "Layout handled event\n";
                MessageBox.Show(message);
                message = "";
            }

            private void theBorder_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
            {
                message += "theBorder handled event\n";
            }

            private void theStackPanel_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
            {
                message += "theStackPanel handled event\n";
            }

            private void theRectangle_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
            {
                message += "theRectangle handled event\n";
            }

        }
    }

AddHandler Method

"The AddHandler method provides a way to always invoke a specified handler, even if the routed event has already been marked as handled."

  • The AddHandler method adds a routed event handler for a specified routed event, adding the handler to the handler collection on the current element. Specify handledEventsToo as true to have the provided handler be invoked for routed event that had already been marked as handled by another element along the event route.

  • Below is the constructor code from MainPage.xam.cs which contains a call to the AddHandler method, which causes any controls on the page to handle the MouseLeftButtonDownEvent event:

            public MainPage()
            {
                InitializeComponent();
                this.AddHandler(UIElement.MouseLeftButtonDownEvent,
                   new MouseButtonEventHandler (LayoutRoot_MouseRightButtonDown), true);

            }

  • AddHandler Syntax:

    public void AddHandler(RoutedEvent routedEvent, Delegate handler, bool handledEventsToo)


Reference Articles