Showing posts with label Windows Phone apps. Show all posts
Windows phone c# code to Call and Message from windows phone
C# code for sending message:
SmsComposeTask smsComposeTask = new SmsComposeTask();
smsComposeTask.To = "6786543672"; // phone number to whom the sms is to be sent
smsComposeTask.Show(); // this will invoke the native sms edtior
C# code to make a call:
phoneCallTask.PhoneNumber = "6786543672";
phoneCallTask.DisplayName = "Name";
phoneCallTask.Show();
Windows phone C# code to get selected data by selecting checkbox in listbox
Here is the example to get selected data by selecting checkbox in listbox:
<ListBox Height="600" Name="listBox1" Margin="0,0,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid x:Name="grid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<CheckBox x:Name="cb" Tag="{Binding PhoneNo}" IsChecked="{Binding IsSelected}" IsEnabled="True" Checked="cb_Checked_1" Unchecked="cb_Unchecked_1" Grid.Column="0" />
<TextBlock x:Name="Txt_Name" Grid.Column="1" Text="{Binding Name}" VerticalAlignment="Center"/>
<TextBlock x:Name="Txt_PhNo" Grid.Column="2" Text="{Binding PhoneNo}" VerticalAlignment="Center" />
<TextBlock Grid.Column="3" Text="{Binding Location}" VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
string option_selected = "";
int check_count = 0;
private void cb_Checked_1(object sender, RoutedEventArgs e)
{
check_count = 0;
option_selected = "";
SearchElement(listBox1);
string s = " Total Selected Checkboxes : " + check_count.ToString()
+ Environment.NewLine + " Value Associated : " + option_selected;
}
private void cb_Unchecked_1(object sender, RoutedEventArgs e)
{
check_count = 0;
option_selected = "";
SearchElement(listBox1);
string s = " Total Selected Checkboxes : " + check_count.ToString()
+ Environment.NewLine + " Value Associated : " + option_selected;
}
private void SearchElement(DependencyObject targeted_control)
{
var count = VisualTreeHelper.GetChildrenCount(targeted_control); // targeted_control is the listbox
if (count > 0)
{
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(targeted_control, i);
if (child is CheckBox) // specific/child control
{
CheckBox targeted_element = (CheckBox)child;
if (targeted_element.IsChecked == true)
{
if (option_selected != "")
{
option_selected = option_selected + " , " + targeted_element.Tag;
}
else
{
// get the value associated with the "checked" checkbox
option_selected = targeted_element.Tag.ToString();
}
// count the number of "Checked" checkboxes
check_count = check_count + 1;
return;
}
}
else
{
SearchElement(child);
}
}
}
else
{
return;
}
}
xaml code
<ListBox Height="600" Name="listBox1" Margin="0,0,0,0" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid x:Name="grid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<CheckBox x:Name="cb" Tag="{Binding PhoneNo}" IsChecked="{Binding IsSelected}" IsEnabled="True" Checked="cb_Checked_1" Unchecked="cb_Unchecked_1" Grid.Column="0" />
<TextBlock x:Name="Txt_Name" Grid.Column="1" Text="{Binding Name}" VerticalAlignment="Center"/>
<TextBlock x:Name="Txt_PhNo" Grid.Column="2" Text="{Binding PhoneNo}" VerticalAlignment="Center" />
<TextBlock Grid.Column="3" Text="{Binding Location}" VerticalAlignment="Center"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
C# code:
string option_selected = "";
int check_count = 0;
private void cb_Checked_1(object sender, RoutedEventArgs e)
{
check_count = 0;
option_selected = "";
SearchElement(listBox1);
string s = " Total Selected Checkboxes : " + check_count.ToString()
+ Environment.NewLine + " Value Associated : " + option_selected;
}
private void cb_Unchecked_1(object sender, RoutedEventArgs e)
{
check_count = 0;
option_selected = "";
SearchElement(listBox1);
string s = " Total Selected Checkboxes : " + check_count.ToString()
+ Environment.NewLine + " Value Associated : " + option_selected;
}
private void SearchElement(DependencyObject targeted_control)
{
var count = VisualTreeHelper.GetChildrenCount(targeted_control); // targeted_control is the listbox
if (count > 0)
{
for (int i = 0; i < count; i++)
{
var child = VisualTreeHelper.GetChild(targeted_control, i);
if (child is CheckBox) // specific/child control
{
CheckBox targeted_element = (CheckBox)child;
if (targeted_element.IsChecked == true)
{
if (option_selected != "")
{
option_selected = option_selected + " , " + targeted_element.Tag;
}
else
{
// get the value associated with the "checked" checkbox
option_selected = targeted_element.Tag.ToString();
}
// count the number of "Checked" checkboxes
check_count = check_count + 1;
return;
}
}
else
{
SearchElement(child);
}
}
}
else
{
return;
}
}
Windows phone 8 C# code to check network or internet or wifi availablility
C# code in Windows phone 8 apps to display message in message box saying Network not available to update data when internet is not available in phone.
bool isNetwork = NetworkInterface.GetIsNetworkAvailable();
if (!isNetwork)
{
MessageBox.Show("Network not available to update data");
}
else {
//code to work when network is available
}
bool isNetwork = NetworkInterface.GetIsNetworkAvailable();
if (!isNetwork)
{
MessageBox.Show("Network not available to update data");
}
else {
//code to work when network is available
}
Windows phone 8 Sqlite queries to insert update delete in C# xaml app
C# code in windows phone 8 app with sqlite commands
string dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "db.sqlite");
private void BtnUpdate_OnClick(object sender, RoutedEventArgs e)
{
using (var db = new SQLiteConnection(dbPath))
{
db.DeleteAll<RechargePlansData>();
db.RunInTransaction(() =>
{
for (int i = 0; i < d.l.Count; i++)
{
db.Insert(new RechargePlansData() { statename = 1, networkname = 1, categoryname = 1, amount = "2000", talktime = "2200", validity = "1 months", descriptiondata = "voda description1" });
}
});
}
private void BtnUpdate_OnClick(object sender, RoutedEventArgs e)
{
using (var db = new SQLiteConnection(dbPath))
{
var existing = db.Query<Person>("select * from Person").FirstOrDefault();
if (existing != null)
{
existing.FirstName = "Denis";
db.RunInTransaction(() =>
{
db.Update(existing);
});
}
}
}
private void BtnDelete_OnClick(object sender, RoutedEventArgs e)
{
using (var db = new SQLiteConnection(dbPath))
{
var existing = db.Query<Person>("select * from Person").FirstOrDefault();
if (existing != null)
{
db.RunInTransaction(() =>
{
db.Delete(existing);
});
}
}
}
C# code in RechargePlansData class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WP8Sqlite
{
class RechargePlansData
{
[SQLite.PrimaryKey, SQLite.AutoIncrement]
public int Id { get; set; }
public int statename { get; set; }
public int networkname { get; set; }
public int categoryname { get; set; }
public string amount { get; set; }
public string talktime { get; set; }
public string validity { get; set; }
public string descriptiondata { get; set; }
}
}
Windows Phone 8 C# code to consume asmx webservice with ADO.NET code
I added web service in references of my windows phone 8 app.
DbakingsReference is the ServiceName i gave. This is used as namespace in C# code.
RechargePlansService is the class inside my webservice.
GetData is the web method i created in webservice which returns data in form of a user defined type named data.
//return type
DbakingsReference is the ServiceName i gave. This is used as namespace in C# code.
RechargePlansService is the class inside my webservice.
GetData is the web method i created in webservice which returns data in form of a user defined type named data.
Here is the code in web service asmx file containing web method that returns data which is retreived from sql server database using ADO.NET
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Collections;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class RechargePlansService : System.Web.Services.WebService {
public RechargePlansService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlconnection"].ConnectionString);
[WebMethod]
public data GetData()
{
data d = new data(); ;
SqlCommand cmd = new SqlCommand("select * from tbl_data", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
int i = 0;
List<string> l1 = new List<string>();
for ( i = 0; i < ds.Tables[0].Rows.Count; i++)
{
l1.Add( ds.Tables[0].Rows[i][0].ToString() + "," + ds.Tables[0].Rows[i][1].ToString() );
}
d.l = l1;
return d;
}
//return type
public class data
{
public List<string> l;
}
}
Code in Windows phone app to display data retreived from web service in a message box
private void Btn1_Click(object sender, EventArgs e)
{
DbakingsReference.RechargePlansServiceSoapClient MyClient = new DbakingsReference.RechargePlansServiceSoapClient();
MyClient.GetDataCompleted += MyClient_GetDataCompleted;
MyClient.GetDataAsync();
}
private void MyClient_GetDataCompleted(object sender, DbakingsReference.GetDataCompletedEventArgs e)
{
DbakingsReference.data d= e.Result;
MessageBox.Show ( d.l[0]);
}
XAMLC# code to play audio using MediaElement in Windows Phone 8 apps
Playing Audio using MediaElement
Add audio files required to Assets folder.
XAML code for button with click event and media element with audio file as source
XAML code for button with click event and media element with audio file as source
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<StackPanel>
<Button Height="200" Width="200"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Background="Red"
Click="Button_Click_1"
>Play</Button>
<Button Height="200" Width="200"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Background="Red"
Click="Button_Click_2"
>Stop</Button>
</StackPanel>
<MediaElement x:Name="MElement"
Source="/Assets/Krrish.mp3"
Volume="50"
AutoPlay="False"
>
</MediaElement>
</Grid>
CSharp.net code in MainPage.xaml.cs page inside button click to play audio
private void Button_Click_1(object sender, RoutedEventArgs e)
{
MElement.Play();
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
MElement.Stop();
Creating XAML Button inside Grid using C# code
C# Code to create button inside grid
public partial class MainPage : PhoneApplicationPage{
// Constructor
public MainPage()
{
InitializeComponent();
Button Btn1=new Button();
Btn1.Width=200;
Btn1.Height=200;
Btn1.HorizontalAlignment=HorizontalAlignment.Left;
Btn1.VerticalAlignment=VerticalAlignment.Top ;
Btn1.Name = "Btn1";
Btn1.Content="Click ME";
Btn1.Margin = new Thickness(100, 0, 0, 0);
ContentPanel.Children.Add(Btn1);
}
The above C# code is equal to below XAML code
Windows Phone 8 Login Page Design XAML Code
XAML code given below can be used in the windows phone 8 portrait page to change it into a login page which takes emailid and password from the user.
</Grid>
XAML code for login page in windows phone
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid.RowDefinitions>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
<RowDefinition Height="auto"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="Emaild" Margin="15"></TextBlock>
<TextBox Grid.Row="1" x:Name="TxtLoginEmailid" Margin="5"></TextBox>
<TextBlock Grid.Row="2" Text="Password" Margin="15"></TextBlock>
<TextBox Grid.Row="3" x:Name="TxtLoginPwd" Margin="5"></TextBox>
<Button Grid.Row="4" x:Name="BtnLogin" Content="Login" Margin="5" ></Button>
<HyperlinkButton x:Name="HLRegister" Grid.Row="5" Content="Click here to Register"></HyperlinkButton>
Splash Screen for windows phone 8 apps
Create an image with 720*1280 px.
Save it as SplashScreenImage.jpg in the root folder of your project then it will be automatically applied as splash screen for your app.
Generally use it when first page of your app takes some time to load.
This resolution is recommended as it will automatically scale to all other resolutions of windows phones.
Save it as SplashScreenImage.jpg in the root folder of your project then it will be automatically applied as splash screen for your app.
Generally use it when first page of your app takes some time to load.
This resolution is recommended as it will automatically scale to all other resolutions of windows phones.
Windows Phone 8 apps development with Phone gap cardova
Apache cardova is used to create cross platform mobile applications.
latest version of phonegap from 3.0 is called as cardova.
It is an open source platform and used by the applications of ios, windows phone, android, blackberry and so on.
For working with phone gap applications you have to be familiar with html5 js and css.
Install phonegap from http://phonegap.com/
Install visual studio 2012 windows phone 8 express
http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-products#d-express-for-windows-phone
Install Node.js
http://nodejs.org/
set the path:
Path settings
computer
properties
advanced settings
Environment Variables
path Edit
append below path after npm;
c:\windows\microsoft.net\framework\v4.03.0000(go this path in your system and paste it)
ok
link to download and install phone gap in windows 8
http://phonegap.com/install/
latest version of phonegap from 3.0 is called as cardova.
It is an open source platform and used by the applications of ios, windows phone, android, blackberry and so on.
For working with phone gap applications you have to be familiar with html5 js and css.
Install phonegap from http://phonegap.com/
http://www.microsoft.com/visualstudio/eng/products/visual-studio-express-products#d-express-for-windows-phone
Install Node.js
http://nodejs.org/
set the path:
Path settings
computer
properties
advanced settings
Environment Variables
path Edit
append below path after npm;
c:\windows\microsoft.net\framework\v4.03.0000(go this path in your system and paste it)
ok
link to download and install phone gap in windows 8
http://phonegap.com/install/
npm install -g phonegap
commands to create cordova sample project in command prompt to customize in visual studio 2012
cordova create sample bin.debug.x app1
cd sample
cordova platform add wp8
cordova build wp8
http://docs.phonegap.com/en/3.1.0/cordova_compass_compass.md.html#Compass
http://cordova.apache.org/docs/en/3.1.0/cordova_camera_camera.md.html#Camera
phonegap api references link for phonegap js code and commands to install plugins for both phonegap and cordova
http://docs.phonegap.com/en/3.1.0/cordova_compass_compass.md.html#Compass
Use only cordova javascript codes from the examples if you are working with cordova
http://cordova.apache.org/docs/en/3.1.0/cordova_camera_camera.md.html#Camera
Windows phone 8 apps C# navigation code with sending values from one page to other
Windows phone 8 apps C# navigation code with sending values from one page to other
Here is the code to under a button click to navigate from mainpage.xaml to Plans.xamlIn the below code hello is the text present inside a string planCategory.
the value inside planCategory is sent to the plans.xaml page using the below code.
string planCategory="Airtel,SMSPlan";
NavigationService.Navigate(new Uri("/Plans.xaml?msg=planCategory , UriKind.Relative));
Code in second page ie., Plans.xaml to display text which is sent in the before page
int i=0;
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string msg = "";
if (NavigationContext.QueryString.TryGetValue("msg", out msg))
i=msg.IndexOf(',');
PageTitle.Text = msg.Substring (0,i);
PlanCategory.Text = msg.Substring(i+1, msg.Length - i);
}
Windows Phone 8 apps development Part-6 Appbar
Windows Phone 8 Application Bar
Application bar is simply called as app bar which contains row of icons at the bottom of the phone screen. It is used to display most commonly used tasks.We can create it directly using GUI properties
It should be used insead of creating new menus.
It can have upto 4 buttons and optional menu which comes out when user swipes up the menu.
It will be displayed on the side of screen in landscape mode using builtin animations when user switch the orientation.
We can generate events for icons and menu items inside app bar to write C# code to perform actions.
IconUrl is the property used to display icon images.
Opacity property is used to make the app bar transparent if its value is less than 1. If opacity is 1 displayed page is occupies the rest of the screen which is not covered by appbar.
In the below example there are two app bar icons and two menu items. Items are displayed out When the user click on three dots present on appbar.
When user click on any icon or menu item a message box will be displayed using C# code.
Example of an app bar with icons, menu items with events in MainPage.xaml page
Create an windows phone app which comes with MainPage.xaml. In the xaml code page add app bar code as shown in the below
<phone:PhoneApplicationPage
x:Class="PhoneApp1.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"
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 Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="Main Page" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
</Grid>
</Grid>
<phone:PhoneApplicationPage.ApplicationBar>
<shell:ApplicationBar Mode="Default" Opacity="1.0" IsMenuEnabled="True" IsVisible="True">
<shell:ApplicationBarIconButton Click="Save_Click" IconUri="/Images/save.png" Text="save" />
<shell:ApplicationBarIconButton Click="Settings_Click" IconUri="/Images/settings.png" Text="settings" />
<shell:ApplicationBar.MenuItems>
<shell:ApplicationBarMenuItem Click="MenuItem1_Click" Text="menu item 1" />
<shell:ApplicationBarMenuItem Click="MenuItem2_Click" Text="menu item 2" />
</shell:ApplicationBar.MenuItems>
</shell:ApplicationBar>
</phone:PhoneApplicationPage.ApplicationBar>
</phone:PhoneApplicationPage>
C# code to handle events of element present in app bar
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PhoneApp1.Resources;
namespace PhoneApp1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
//BuildLocalizedApplicationBar();
}
private void Save_Click(object sender, EventArgs e)
{
MessageBox.Show("Save button works!");
}
private void Settings_Click(object sender, EventArgs e)
{
MessageBox.Show("Settings button works!");
}
private void MenuItem1_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu item 1 works!");
}
private void MenuItem2_Click(object sender, EventArgs e)
{
MessageBox.Show("Menu item 2 works!");
}
}
}
Windows Phone 8 apps development Part-5 Navigation
Windows Phone 8 Page Navigation
XAML apps on windows phone use page based navigation model which is similar to web page model. Pages are stateless and they are identified by URI.
Navigation to other pages in Windows Phone
Create a windows phone basic application which comes with a default page named as MainPage.xaml.
Create another page by adding new item (Pivot page) to your solution explorer named as Page1.xaml.
In MainPage.xaml add a xaml hyperlink button control and generate click event to write the below code using which user can navigate from MainPage.xaml to Page1.xaml.
Example to Navigate - XAML code for hyperlink button
<HyperlinkButton Content="HyperlinkButton" Click="HyperlinkButton_Click_1"/>
C# code under hyperling button click event
private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new Uri ("/Page1.xaml",UriKind.Relative ));
}
Navigation to before page
Application provides controls to navigate to preceding page and other pages.
The hardware back button is also used to navigate to preceding page.
Sometimes we have to override the hardware back button .If there is a panel opened then user expects the panel to be closed with a click on back button. But, if it redirect to the before page that creates a problem so in those cases we have to override the hardware button.
Example to navigate to before page
Create a new phone application with two pages MainPage.xaml and Page1.xaml.
Add HyperlinkButton controls in each page.
In the first page Hyperlink button click event write the code to navigate to Page1.xaml as shown in the before example.
Xaml code and C# code in Page1.xaml to navigate to MainPage.xaml with a click on hyperlinkbutton
<HyperlinkButton Content="Back" Click="HyperlinkButton_Click_1"/>
private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
{
NavigationService.GoBack();
Exit or Close an app
Don't Use close or exit buttons in your app because users know that they can use back button or start button to leave your app. When user use back button to exit your app your app will be closed. If user launches other app your app will be deactivated. Windows phone automatically handles these events and manages the app life cycle and resources.
When user click on back button when he is on the first page of the app then closing event is raised and the app will be closed.
When the user click on start button deactivated event will be raised and the app will be deactivated.
If the app is deactivated the app will be on back state. It may be launched again from the start screen.
The app in back state can be removed because of lack of resources or uninstallation of app or reboot of device.
The app can be terminated because of unhandled exception or calling terminate method.
It an app is terminated it will be removed from the back state.
XAML apps on windows phone use page based navigation model which is similar to web page model. Pages are stateless and they are identified by URI.
Navigation to other pages in Windows Phone
Create a windows phone basic application which comes with a default page named as MainPage.xaml.
Create another page by adding new item (Pivot page) to your solution explorer named as Page1.xaml.
In MainPage.xaml add a xaml hyperlink button control and generate click event to write the below code using which user can navigate from MainPage.xaml to Page1.xaml.
Example to Navigate - XAML code for hyperlink button
<HyperlinkButton Content="HyperlinkButton" Click="HyperlinkButton_Click_1"/>
C# code under hyperling button click event
private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
{
this.NavigationService.Navigate(new Uri ("/Page1.xaml",UriKind.Relative ));
}
Navigation to before page
Application provides controls to navigate to preceding page and other pages.
The hardware back button is also used to navigate to preceding page.
Sometimes we have to override the hardware back button .If there is a panel opened then user expects the panel to be closed with a click on back button. But, if it redirect to the before page that creates a problem so in those cases we have to override the hardware button.
Example to navigate to before page
Create a new phone application with two pages MainPage.xaml and Page1.xaml.
Add HyperlinkButton controls in each page.
In the first page Hyperlink button click event write the code to navigate to Page1.xaml as shown in the before example.
Xaml code and C# code in Page1.xaml to navigate to MainPage.xaml with a click on hyperlinkbutton
<HyperlinkButton Content="Back" Click="HyperlinkButton_Click_1"/>
private void HyperlinkButton_Click_1(object sender, RoutedEventArgs e)
{
NavigationService.GoBack();
Exit or Close an app
Don't Use close or exit buttons in your app because users know that they can use back button or start button to leave your app. When user use back button to exit your app your app will be closed. If user launches other app your app will be deactivated. Windows phone automatically handles these events and manages the app life cycle and resources.
When user click on back button when he is on the first page of the app then closing event is raised and the app will be closed.
When the user click on start button deactivated event will be raised and the app will be deactivated.
If the app is deactivated the app will be on back state. It may be launched again from the start screen.
The app in back state can be removed because of lack of resources or uninstallation of app or reboot of device.
The app can be terminated because of unhandled exception or calling terminate method.
It an app is terminated it will be removed from the back state.
Windows Phone 8 apps development Part-5 Tiles, Templates, Resolutions, Splash Screen
Windows Phone 8 Tiles
Resolutions supported in Windows Phone 8
WVGA - 480 * 800 px - 15:9(Aspect ratio)WXGA - 768 * 1260 px - 15:9(Aspect ratio)
720p - 720 * 1280 px - 16:9(Aspect ratio)
So, because of this different resolutions support in WP8 the height and width of controls shouldn't be hard coded.
Tiles
Tiles are pinned to the start screen and it is the used to launch the app with a tap on it.All apps will have atleast one tile known as default tile.
Tiles may contain text/image content and the content may be static or dynamic.
There are 3 tile sizes and also three title templates.
Sizes - Small, medium and Wide.
Tile sizes and resolutions
Small - 159 * 159 px (Flip and Cycle), 110 * 110 px (Ionic)
Medium - 336 * 336 px(Flip and Cycle), 202 * 202 px (Ionic)
Wide - 691 * 336 px(Flip and Cycle), NA (Ionic)
Templates - Flip, iconic, cycle
Flip - flips from front to back
iconic - clean layout W8 style with 2 colors and 2d styles
cycle - 9 images can be cycled from local or cloud resources
You can add three images for tiles and to add large tile you have to select the checkbox support for large tiles.
Live Tiles
Live tiles can be updated with the new information from the app.We can display most useful information on it from the running app (or) using scheduled tasks when app is not running (or) using push notifications.
Secondary Tiles
Secondary tiles are created programmatically which represent a page and can launch any page in your app.
Splash Screen
Add image named as SplashScreenImage.jpg with 768 * 1280 px. It will automatically scale to all screens sizes.
App Icons
Resolution for app icon is 100 * 100
For app icons include images for WXGA resolutions. They will automatically scale to WXGA, WVGA and 720px screens.
Windows Phone 8 orientation Resolutions
Windows phone supports Potrait, Landscape left and Landscape right orientations.You can check your app in different orientations on emulator.
All apps in windows phone need not support both landscape and potrait orientation.
You can configure apps to support both orientations.
There are two properties SupportedOrientations and Orientation in phone application page which allows you to select orientation options.
Your application can bind to an event which is fired when orientation changes.
Stack panel with scroll viewer will allow the user to scroll the content based on the orientation.
Windows Phone 8 Resolutions
It comes in 3 resolutions.
In WP8 we have 3 screen resolutions
wvga 800*480 15:9
wxga 1280 * 768 15:9(New)
720p 1280*720 16:9(New)
No need of creating three UI designs for these three resolutions. OS applies a scale factor to the actual resolution of apps.
Use auto and * for specifing the height and width of grid for good layout.
auto - value based on the content inside it.
* - value is equal to the remaining space available.
If multiple rows are using * then the remaining space is equally used by them.
You should supply images targeting the WXGA (1280 * 768) screen as they will automatically scale down to WVGA phones and still look great on 720p.
Include images at each of the 3 resolutions in your project.
Write code to load image at runtime appropriate for the current screen resolution.
At runtime, get Application.Current.Host.Content.ScaleFactor to determine the resolution of the screen on the current phone, returns 100 for WVGA, 160 for WXGA and 150 form 720p
Windows Phone 8 apps development Part-4 HTML5
Windows Phone 8 HTML5 apps development
In Windows Phone 8 we have a template named Windows Phone HTML5 app using which we can create an app using HTML5 with CSS3 that is launched using IE10 browser.
In that app MainPage.xaml is launched first which contains webbrowser control that displays HTML5 content.
In that app MainPage.xaml is launched first which contains webbrowser control that displays HTML5 content.
- See more at: http://dbakings.com/phone/WindowsPhone8HTML5.aspx#sthash.6mK3EacX.dpuf
In Windows Phone 8 we have a template named Windows Phone HTML5 app using which we can create an app using HTML5 with CSS3 that is launched using IE10 browser.
In that app MainPage.xaml is launched first which contains webbrowser control that displays HTML5 content.
Windows Phone 8 HTML5 apps development
In Windows Phone 8 we have a template named Windows Phone HTML5 app using which we can create an app using HTML5 with CSS3 that is launched using IE10 browser.In that app MainPage.xaml is launched first which contains webbrowser control that displays HTML5 content.
- See more at: http://dbakings.com/phone/WindowsPhone8HTML5.aspx#sthash.6mK3EacX.dpuf
Windows Phone 8 apps development Part-3 XAML
Introduction to XAML
XAML stands for Extensible application markup language.
It is a case sensitive language.
.xaml is the extension for xaml files.
It is used for declaring windows phone UI along with WPF and silverlight.
XAML elements are objects in the System.Windows.Controls namespace.
Every element contains properties that defines how it appears on the screen like width, height, color... These values of properties can also be changed using C# code which effects in UI.
xmlns stands for xml namespaces used to add namespaces in xaml.
x:Name property is used to specify name of an element using which you can control that element using C# code.
Declaring xaml object
xaml object is created using opening and closing tags.
opening tag contain object name surrounded by angular braces and closing tag contain object name with forward slash as suffix surrounded by angular braces.
<Canvas> </Canvas>
Some of the objects in xaml such as canvas, stack panel, grid,... are capable of holding other controls inside them.
<Canvas> <Rectangle> </Rectangle> </Canvas>
We can also use single tag in place of opening and closing tags for some elements.
<Canvas> <Rectangle /> </Canvas>
We can also declare attributes or properties for the elements within the tags
<Canvas> <Rectangle Name="R1" Width="120" Height="120" Fill="Blue" /> </Canvas>
Everythind you do in XAML can be done with code.
The above object can be created using C# code as follows
Rectangle R1 = new Rectangle( );
R1.Width=120;
R1.Height=120;
R1.Fill = new SolidColorBrush(Colors.Blue);
XAML follows hierarchy in describing elements. It is extensible which allows developers to create their own reusable controls.
Lot of standard controls in the toolbox can be used to design the app without writing XAML.
Toolkit controls are also available which can be used by installing sdk and adding namespace.
Signature controls like panorama, pivot, sticky heads, jumplist, gridview.
It is a case sensitive language.
.xaml is the extension for xaml files.
It is used for declaring windows phone UI along with WPF and silverlight.
XAML elements are objects in the System.Windows.Controls namespace.
Every element contains properties that defines how it appears on the screen like width, height, color... These values of properties can also be changed using C# code which effects in UI.
xmlns stands for xml namespaces used to add namespaces in xaml.
x:Name property is used to specify name of an element using which you can control that element using C# code.
Declaring xaml object
xaml object is created using opening and closing tags.
opening tag contain object name surrounded by angular braces and closing tag contain object name with forward slash as suffix surrounded by angular braces.
<Canvas> </Canvas>
Some of the objects in xaml such as canvas, stack panel, grid,... are capable of holding other controls inside them.
<Canvas> <Rectangle> </Rectangle> </Canvas>
We can also use single tag in place of opening and closing tags for some elements.
<Canvas> <Rectangle /> </Canvas>
We can also declare attributes or properties for the elements within the tags
<Canvas> <Rectangle Name="R1" Width="120" Height="120" Fill="Blue" /> </Canvas>
Everythind you do in XAML can be done with code.
The above object can be created using C# code as follows
Rectangle R1 = new Rectangle( );
R1.Width=120;
R1.Height=120;
R1.Fill = new SolidColorBrush(Colors.Blue);
XAML follows hierarchy in describing elements. It is extensible which allows developers to create their own reusable controls.
Lot of standard controls in the toolbox can be used to design the app without writing XAML.
Toolkit controls are also available which can be used by installing sdk and adding namespace.
Signature controls like panorama, pivot, sticky heads, jumplist, gridview.
Windows phone 8 basic page XAML code
<phone:PhoneApplicationPage
x:Class="Sampleapp.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"
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>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
</Grid>
</Grid>
</phone:PhoneApplicationPage>
Explanation
It contain a grid named as LayoutRoot with Transparent as background color.
It contains two rows with height as auto and *.
auto means that row height is based on the content inside it.
* means the remaining space is the height of the second row.
It contain a stackpanel named as TitlePanel which is present in the row 0 of grid with specific margin.
Stack panel is a control used to hold other controls inside it to get a good design in xaml.
Stack panel holds two textblocks and the other grid row contains nothing.
There is a PhoneApplicationPage class with some sub classes.
Frame contains a page and page contains content.
Each page is identified by URI and every page is stateless.
Prerequisites for developing phone 8 apps
x:Class="Sampleapp.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"
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>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
</Grid>
</Grid>
</phone:PhoneApplicationPage>
Explanation
It contain a grid named as LayoutRoot with Transparent as background color.
It contains two rows with height as auto and *.
auto means that row height is based on the content inside it.
* means the remaining space is the height of the second row.
It contain a stackpanel named as TitlePanel which is present in the row 0 of grid with specific margin.
Stack panel is a control used to hold other controls inside it to get a good design in xaml.
Stack panel holds two textblocks and the other grid row contains nothing.
There is a PhoneApplicationPage class with some sub classes.
Frame contains a page and page contains content.
Each page is identified by URI and every page is stateless.
Prerequisites for developing phone 8 apps
Install Visual Studio 2012 phone express with SDK 8.0 for developing windows phone 8 apps.
Open visual studio
Steps Creating first phone 8 app
file – new – project – select C# Windows Phone
Select Template Windows Phone app
Open visual studio
Steps Creating first phone 8 app
file – new – project – select C# Windows Phone
Select Template Windows Phone app
Name of your project will be PhoneApp1 by default
When you click on Ok you will see a dialog asking for selection of Target Windows Phone OS. You can select 8.0 and click on Ok for windows phone 8 app.
Screens here are called pages.
MainPage.xaml is the first default page in which we will work and you can add more page to navigate from one page to other.
Basic XAML code in MainPage.xaml page
Screens here are called pages.
MainPage.xaml is the first default page in which we will work and you can add more page to navigate from one page to other.
Basic XAML code in MainPage.xaml page
<phone:PhoneApplicationPage
x:Class="PhoneApp1.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"
FontFamily="{StaticResourcePhoneFontFamilyNormal}"
FontSize="{StaticResourcePhoneFontSizeNormal}"
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 Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
<TextBlock Text="page name" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel"Grid.Row="1" Margin="12,0,12,0">
</Grid>
</Grid>
</phone:PhoneApplicationPage>
<Grid x:Name="ContentPanel"Grid.Row="1" Margin="12,0,12,0">
<Button>Click ME</Button>
</Grid>
This button will occupy the entire ContentPanel.
Adding XAML button with specific size inside Grid
This button will occupy the entire ContentPanel.
Adding XAML button with specific size inside Grid
<Grid x:Name="ContentPanel"Grid.Row="1" Margin="12,0,12,0">
<Button Height="200" Width="200">Click ME</Button>
</Grid>
Now this square shaped button will be aligned at the center of the grid.
Now this square shaped button will be aligned at the center of the grid.
To align it at the top left corner of the grid use the below code
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Height="200" Width="200"
VerticalAlignment="Top"
HorizontalAlignment="Left"
>Click ME</Button>
</Grid>
Now I will add background color to the button using below xaml code
<Grid x:Name="ContentPanel"Grid.Row="1" Margin="12,0,12,0">
<Button Height="200" Width="200"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Background="Red"
>Click ME</Button>
</Grid>