Getting Started With Event Handling in Windows Phone 7


Introduction

In this article we are going to explore how to work with events in Windows Phone 7 and how to handle them in Windows Phone 7. Further in details we will learn what an event is. It is mainly something known to happening that can cause some reaction. In this article we are going to explore how we can make a touch event in Windows Phone 7 and how we will implement such type of application in Windows Phone 7. Further in this we will see that whenever we will click on the Windows Phone 7 default screen then it will make a colored ellipse as well. That will continue until you stop clicking on the screen. Further we will discuss that an event is a mechanism via which a class can notify its clients when something happens. For example when you click on a button in Windows Phone 7, a button-click-event notification is sent to the window hosting the button. Events are declared using delegates. In this we are using a brush such as GradientBrush which is used to fill the color inside the ellipse. It will show a different color on every change of the touch point which will you see in the article description. So to do that follow the steps given below.

Step 1: In this step first of all we have to open a Windows Phone application; let us see how you will open it.

  • Go to Visual Studio 2010
  • File->New->Project
  • Select the template named as Silverlight for Windows Phone
  • Select the Windows Phone application
  • Give it a name as you want.   

Step_1_1figgg.jpg

img.gif

Step 2: In this step we have to make an Event and after that we will add a handler to the event, which is given below. Further we have to know about the Touch Class; it's a class which provides an application level service to get the touch input from the OS and will generate the touch event also. It takes a method reference as an argument which is given below.

Code:

public MainPage()

 {
    InitializeComponent();
    Touch.FrameReported += new TouchFrameEventHandler(MyTPoint_FrameReported);
 }

 

Step 3: As we have seen inside the event we have a method argument named as MyTPoint_FrameReported which will be defined in the code given below. Within a handler we need to get all touch points and draw ellipses filled with specific colors for each of them.  

 

Code:

 

void MyTPoint_FrameReported(object sender, TouchFrameEventArgs e)

 {
    TouchPointCollection TPointC = e.GetTouchPoints(mycanvas);

    int No_of_TPoint = 1;

    TPointC.ToList().ForEach(x => drawmyelpse(x.Position, No_of_TPoint++));
 }

 

Step 4: In this step we have to write the code for drawing an ellipse via code whenever we touch or click on the screen of Windows Phone 7 and the related code is given below.

 

Code:

private void drawmyelpse(Point p, int No_of_TPoint)

 {
     Ellipse myelpse = new Ellipse()

     {
         Fill = get_col_brush(No_of_TPoint),

         Height = 100,

         Width = 100

     };

     myelpse.Tag = DateTime.Now;

     Canvas.SetLeft(myelpse, p.X - 36);

     Canvas.SetTop(myelpse, p.Y - 36);

     mycanvas.Children.Add(myelpse);
 }
 

Step 5: In this step we have to take the brush for setting the color as you wish and it changes the color whenever the number of touch points increases gradually. Further the code is given below.

Code:

private GradientBrush get_col_brush(int No_of_TPoint)

 {

     Color mycolor = Colors.Transparent;
     if (No_of_TPoint == 1)

         return new RadialGradientBrush(Colors.Green, mycolor);

     else if (No_of_TPoint == 2)

         return new RadialGradientBrush(Colors.Red, mycolor);

     else if (No_of_TPoint == 3)

         return new RadialGradientBrush(Colors.Cyan, mycolor);

     else if (No_of_TPoint == 4)

         return new RadialGradientBrush(Colors.Blue, mycolor);

     else

         return new RadialGradientBrush(Colors.Blue, mycolor);
 }

 

Step 6: In this step we will see that if our current page is no longer the active page in the frame then we can remove all the ellipses from the screen. In that case we simply need to override the OnNavigatedFrom method and clear the children of the canvas. 

 

Code:

 

protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)

 {

     this.mycanvas.Children.Clear();

     base.OnNavigatedFrom(e);

 }

 

Step 8: In this step we will see the complete code for the MAinPage.xaml.cs file which is given below.

 

Complete Code:

 

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;

using Microsoft.Phone.Controls;
namespace multitouch

{

    public partial class MainPage : PhoneApplicationPage

    {

        // Constructor

        public MainPage()

        {

            InitializeComponent();

            Touch.FrameReported += new TouchFrameEventHandler(MyTPoint_FrameReported);

        }

        void MyTPoint_FrameReported(object sender, TouchFrameEventArgs e)

        {

            TouchPointCollection TPointC = e.GetTouchPoints(mycanvas);

            int No_of_TPoint = 1;

            TPointC.ToList().ForEach(x => drawmyelpse(x.Position, No_of_TPoint++));

        }
        private void drawmyelpse(Point p, int No_of_TPoint)

        {

            Ellipse myelpse = new Ellipse()

            {

                Fill = get_col_brush(No_of_TPoint),

                Height = 100,

                Width = 100

            };

            myelpse.Tag = DateTime.Now;

            Canvas.SetLeft(myelpse, p.X - 36);

            Canvas.SetTop(myelpse, p.Y - 36);

            mycanvas.Children.Add(myelpse);

        }
        private GradientBrush get_col_brush(int No_of_TPoint)

        {

            Color mycolor = Colors.Transparent;

 

            if (No_of_TPoint == 1)

                return new RadialGradientBrush(Colors.Green, mycolor);

            else if (No_of_TPoint == 2)

                return new RadialGradientBrush(Colors.Red, mycolor);

            else if (No_of_TPoint == 3)

                return new RadialGradientBrush(Colors.Yellow, mycolor);

            else if (No_of_TPoint == 4)

                return new RadialGradientBrush(Colors.Blue, mycolor);

            else

                return new RadialGradientBrush(Colors.Blue, mycolor);

        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)

        {

            this.mycanvas.Children.Clear();

            base.OnNavigatedFrom(e);

        }
    }
}

 

Step 9: In this step you just see the code for the MainPage.xaml file which is given below.

 

MainPage.xaml Code:

 

<phone:PhoneApplicationPage

    x:Class="multitouch.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"

    FontFamily="{StaticResource PhoneFontFamilyNormal}"

    FontSize="{StaticResource PhoneFontSizeNormal}"

    Foreground="{StaticResource PhoneForegroundBrush}"

    SupportedOrientations="Portrait" Orientation="Portrait"

    shell:SystemTray.IsVisible="True">
    <!--LayoutRoot is the root grid where all page content is placed-->

    <Grid x:Name="LayoutRoot" Background="Transparent">

        <Grid.RowDefinitions>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="*"/>

        </Grid.RowDefinitions>

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

            <TextBlock x:Name="PageTitle" Text="My Touch App" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"

                       FontFamily="Comic Sans MS" FontSize="56" Height="84" Width="457">

                <TextBlock.Foreground>

                  <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">

                    <GradientStop Color="Black" Offset="0" />

                    <GradientStop Color="#FF60FF38" Offset="1" />

                  </LinearGradientBrush>

                </TextBlock.Foreground>

             </TextBlock>

        </StackPanel>

        <Canvas x:Name="mycanvas" Grid.Row="1" Margin="12,0,12,0">

            <Canvas.Background>

                <LinearGradientBrush EndPoint="1,0.5" StartPoint="0,0.5">

                    <GradientStop Color="Black" Offset="0" />

                    <GradientStop Color="White" Offset="1" />

                </LinearGradientBrush>

            </Canvas.Background>

        </Canvas>

    </Grid> 

</phone:PhoneApplicationPage>

 

Step 10: In this step we will see the design of the MainPage.xaml file which is given below.

 

amitdesign.gif

 

Step 11: In this step we will see the output of the following program and the relevant figure is given below.

 

Output 1: Whenever you touch the screen via clicking on it it will changes it's color which is shown in the figure below.


amit.gif

 

Output 2: In this output you just see that whenever the number of touch points increases then it will changes it's color as well you will see in the figure given below.


amit1.gif

 

Output 3: In this output we will also see that the color of touch input changes as shown in the figure given below.


amit2.gif


Here are some other resources which may help you.

 

The installed battery may not be properly connected to the computer

How to handle Manipulation Events and Properties in Windows Phone 7

Event Manipulation in Touch screen for Windows Phone 7

Getting Started With AdControl in Windows Phone 7

How to handle Drop-Down event in Repeater control 

Up Next
    Ebook Download
    View all
    Learn
    View all