Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
Hands On Lab Silverlight for WP7 Hands On Lab ini akan menjelaskan penggunaan VS 2010 untuk membuat aplikasi WP7 menggunakan Silverlight. Materi yang akan dibahas pada HOL ini adalah:
Project and Solution Debugging Program Orientation Page Pages and Navigation Displaying List Of Data & Data Binding
Membuat Aplikasi baru dengan Visual Studio Express for Windows Phone 7 1. Buka Visual Studio 2010 for Windows Phone 7. 2. Pilih File → New Project → Silverlight for Windows Phone → Windows Phone Application. 3. Beri nama SimpleCalculator.
4. Pada Solution Explorer perhatikan file yang digenerate oleh Visual Studio.
1
http://actual-training.com
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
Item App.xaml / App.xaml.cs
MainPage.xaml / MainPage.xaml.cs ApplicationIcon.png Background.png SplashScreenImage.jpg Properties\AppManifest.xml Properties\AssemblyInfo.cs Properties\WMAppManifest.xml
References folder
Deskripsi Mendefinisikan entry point dari aplikasi, inisialisasi resources, dan mendefiniskan style dari user interface. Halaman utama yang berisi desain aplikasi. Icon untuk program yang anda buat yang akan ditampilkan pada application list. Icon yang ditampilkan pada start screen Gambar yang akan dimunculkan ketika aplikasi dijalankan pertama kali. Manifest file yang dibutuhkan untuk membuat application package. Mengandung nama dan versi metadata yang di akan ditanamkan pada general assembly. Manifest file yang mengandung metadata spesifik yang berhubungan dengan Windows Phone Silverlight application, termasuk fitur spesifik yang hanya ada di Silverlight untuk Windows Phone Berisi list library (assembly) yang menyediakan services dan functionality yang dibutuhkan untuk menjalankan aplikasi.
5. Double-click pada halaman MainPage.xaml pada Solution Explorer. Secara default anda dapat melihat tampilan design Windows Phone disisi kiri. Anda dapat menambahkan elemen baru seperti tombol, textbox dengan cara drag n drop kedalam tampilan design atau anda juga dapat menambahkan manual dengan mengetikan kode XAML. 6. Pada StackPanel dengan nama ‘TitlePanel’ ubah teks yang akan ditampilkan sebagai title dari aplikasi yang dibuat: 2
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
http://actual-training.com
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
7. Tambahkan kode berikut pada Grid ‘ContentPanel’, anda dapat menggunakan drag n drop untuk menambahkan control tersebut.
<Button Content="equal" Height="72" HorizontalAlignmen t="Left" Margin="152,221,0,0" Name="btnEqual" VerticalAlignment="T op" Width="160" />
http://actual-training.com
3
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT 8. Kemudian buat sebuah Grid baru dengan nama ContentGrid. Kemudian tulis kode XAML berikut:
<Button Grid.Column="1" Name="btnClick" Content="Click Me" HorizontalAlignment="Right" Margin="10,20,20,20" Padding="4" />
9. Lakukan double click pada tombol ‘equal’, maka VS akan menambahkan property Click dan nama method yang akan dipanggil.
<Button Content="equal" Height="72" HorizontalAlignment="Left" Margin= "152,221,0,0" Name="btnEqual" VerticalAlignment="Top" Width="160" Click="btnEqual_Click" />
10. Pada tampilan ViewCode tulis kode berikut:
private void btnEqual_Click(object sender, RoutedEventArgs e) { int number1 = int.Parse(txtFirstNumber.Text); int number2 = int.Parse(txtSecondNumber.Text); int result = number1 + number2; tbResult.Text = result.ToString();
4
}
http://actual-training.com
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT 11. Sebelum menjalankan aplikasi anda dapat memilih target deployment dari aplikasi anda. Ada dua pilihan yaitu Windows Phone Emulator atau Windows Phone Device.
12. Jalankan aplikasi anda dengan menekan tombol F5. Maka Visual Studio akan menjalankan Emulator.
13. Jika anda melakukan modifikasi aplikasi anda pada Visual Studio, anda tidak perlu untuk menutup emulator. Cukup modifikasi kemudian klik F5 lagi untuk mendeploy aplikasi yang baru. Menambahkan Exception pada Program 1. Tambahkan kode berikut pada method btnEqual_Click
private SolidColorBrush errorBrush = new SolidColorBrush(Colors.Red); private Brush correctBrush = null;
5
private void btnEqual_Click(object sender, RoutedEventArgs e) { http://actual-training.com
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
bool errorFound = false; if (correctBrush == null) { correctBrush = txtFirstNumber.Foreground; } int number1 = 0; int number2 = 0; if (!int.TryParse(txtFirstNumber.Text, out number1)) { txtFirstNumber.Foreground = errorBrush; errorFound = true; } else { txtFirstNumber.Foreground = correctBrush; } if (!int.TryParse(txtSecondNumber.Text, out number2)) { txtSecondNumber.Foreground = errorBrush; errorFound = true; } else { txtSecondNumber.Foreground = correctBrush; } if (errorFound) { tbResult.Text = "Invalid Inputs"; } else { int result = number1+number2; tbResult.Text = result.ToString(); } } Menambahkan Halaman Error 1. Untuk error yang tidak tertangani anda dapat membuat halaman untuk menampilkan error tersebut. 2. Buka aplikasi yang sudah anda buat sebelumnya.
http://actual-training.com
6
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT 3. Klik kanan pada project SimpleCalculator → Add → New Item → pilih template Windows Phone Potrait Page beri nama ‘ErrorPage.xaml’.
4. Pada halaman ‘ErrorPage.xaml’ tuliskan kode berikut:
5. Tekan F7 untuk membuka tampilan View Code, kemudian tambahkan kode berikut:
public partial class ErrorPage : PhoneApplicationPage { http://actual-training.com
7
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
public ErrorPage() { InitializeComponent(); } public static Exception ex; protected override void OnNavigatedTo(System.Windows.Navig ation.NavigationEventArgs e) { ErrorText.Text = "Error : " + ex.Message; } } 6. Pada Solution Explorer klik kanan pada App.xaml dan pilih View Code. 7. Cari event Application_UnhandledException kemudian tambahkan kode berikut:
// Code to execute on Unhandled Exceptions private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { if (System.Diagnostics.Debugger.IsAttached) { // An unhandled exception has occurred; break into the debugger System.Diagnostics.Debugger.Break(); } e.Handled = true; ErrorPage.ex = e.ExceptionObject; (RootVisual as Microsoft.Phone.Controls.PhoneApplicati onFrame).Source = new Uri("/ErrorPage.xaml", UriKind.Relative); } 8. Dengan menuliskan kode diatas maka jika terjadi kesalahan diluar eksepsi yang kita sediakan maka pesan kesalahan tersebut akan ditampilkan di halaman ErrorPage.xaml. 9. Misal anda dapat menginputkan selain angka kedalam textbox pada aplikasi anda. 10. Tekan Ctrl+F5 untuk menjalankan program tanpa debug.
8
http://actual-training.com
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
Navigating Between Pages Untuk melakukan navigasi antar halaman anda dapat menggukan class NavigationService .
9
http://actual-training.com
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT 1. Buat project Windows Phone Application baru dengan nama ‘NavigatingApp’.
2. Kemudian buat halaman baru, pilih Windows Phone Protrait Page dengan nama ‘Page2.xaml’.
3. Pada ‘MainPage.xaml’ tambahkan kode berikut
4. Pada halaman ‘Page2.xaml’ tambahkan kode berikut :
5. Double click ‘hbButton1’ pada MainPage.xaml kemudian tambahkan kode berikut untuk berpindah ke halaman Page2.xaml http://actual-training.com
10
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
private void hbButton1_Click(object sender, RoutedEventArgs e) { this.NavigationService.Navigate( new Uri("/Page2.xaml", UriKind.Relative)); } 6. Double click ‘hbButton2’ pada Page2.xaml untuk kembali ke halaman MainPage.xaml
private void hbButton2_Click(object sender, RoutedEventArgs e) { if (this.NavigationService.CanGoBack) { this.NavigationService.GoBack(); } } Passing Data Through Pages Pada contoh aplikasi ini akan ditunjukan bagaimana menggunakan QueryString untuk melempar nilai antar halaman. 1. Buat project Windows Phone Application dengan nama ‘NavigatingWithParam’. 2. Tambahkan kode xaml berikut pada ‘MainPage.xaml’
<StackPanel Orientation="Vertical"> 3. Tambahkan Windows Phone Potrait Page dengan nama ‘Page2.xaml’, kemudian tambahkan kode xaml berikut.
4. Buat method berikut pada halaman MainPage.xaml.cs untuk redirect ke halaman Page2.xaml sekaligus melempar nilai parameter.
private void HyperlinkButton_Click(object sender, RoutedEventA rgs e) { HyperlinkButton hb = sender as HyperlinkButton; http://actual-training.com
11
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
string url = string.Format("/Page2.xaml?ID={0}", hb.TabInd ex); this.NavigationService.Navigate(new Uri(url, UriKind.Relat ive)); } 5. Tambahkan method tersebut pada event click di HyperlinkButton.
Margin="12,0,12,0"> 1" TabIndex="1" Click 2" TabIndex="2" Click 3" TabIndex="3" Click
6. Pada halaman Page2.xaml.cs, tambahkan kode berikut untuk mengambil nilai yang dikirimkan dari MainPage.xaml.
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { lbText.Text = string.Format("Anda memilih option nomor : {0}", this.NavigationContext.QueryString["ID"]); } Navigating Between Pages Using Global Application Variable 1. Buat Windows Phone Application dengan nama ‘NavigatingWithGlobalVariableApp’. 2. Pada MainPage.xaml tambahkan kode berikut.
<StackPanel> 3. Tambahkan dua halaman yaitu ‘Page2.xaml’ dan ‘Page3.xaml’ 4. Tambahkan property berikut pada App.xaml.cs agar dapat diakses dari halaman yang berbeda.
http://actual-training.com
12
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
public partial class App : Application { /// <summary> /// Provides easy access to the root frame of the Phone Applic ation. /// ///
The root frame of the Phone Application. public PhoneApplicationFrame RootFrame { get; private set; } public bool RedPages { get; set; } /// <summary> /// Constructor for the Application object. /// 5. Klik pada checkbox, kemudian tambahkan kode berikut pada event ‘Checked’.
private void chkRedColor_Checked(object sender, RoutedEventArgs e) { App a = Application.Current as App; a.RedPages = true; ContentPanel.Background = new SolidColorBrush(Colors.Red); } 6. Klik pada checkbox, kemudian tambahkan kode berikut pada event ‘Unchecked’.
private void chkRedColor_Unchecked(object sender, RoutedEventArgs e) { App a = Application.Current as App; a.RedPages = false; ContentPanel.Background = new SolidColorBrush(Colors.Black); } 7. Double click HyperlinkButton ‘hbToPage2’, kemudian tulis kode berikut untuk berpindah ke halaman Page2.xaml.
private void hbToPage2_Click(object sender, RoutedEventArgs e) { this.NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative)); } 8. Double click HyperlinkButton ‘hbToPage3’, kemudian tulis kode berikut untuk berpindah ke halaman Page3.xaml. 9. Pada event load di Page2.xaml, tambahkan kode berikut untuk mengambil nilai dari global var dan mengubah warna background.
http://actual-training.com
13
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { App a = Application.Current as App; if (a.RedPages) ContentPanel.Background = new SolidColorBrush(Colors.Red); } 10. Sama dengan langkah sebelumnya, tambahkan kode berikut pada Page3.xaml.
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) { App a = Application.Current as App; if (a.RedPages) ContentPanel.Background = new SolidColorBrush(Colors.Red); } Navigating with State Untuk menyimpan object yang kompleks agar dapat diakses pada halaman yang berbeda, anda dapat menyimpan di state. Anda dapat menggunakan dictionary state pada object PhoneApplicationServices. 1. Buat Windows Phone Application dengan nama ‘NavigatingWithStateApp’ 2. Pada halaman MainPage.xaml tambahkan kode berikut.
3. Pada Page2.xaml tambahkan kode berikut untuk menambahkan object yang akan disimpan pada state.
<StackPanel>
http://actual-training.com
14
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
<Button x:Name="btnSave" Content="Save" Click="btnSa ve_Click" /> 4. Buat class dengan nama Person.cs
public class Person { public string FirstName { get; set; } public string LastName { get; set; } public string City { get; set; } public Person(){} } 5. Pada MainPage.xaml di event Loaded, tambahkan kode berikut untuk mengecek apakah object ada di state.
private void PhoneApplicationPage_Loaded(object sender, Rout edEventArgs e) { if (PhoneApplicationService.Current.State.ContainsKey("P erson")) { Person p = (Person)PhoneApplicationService.Current.S tate["Person"]; tbMsg.Text = string.Format("Welcome {0} {1} from {2} ", p.FirstName, p.LastName, p.City); } } 6. Tambahkan juga kode berikut untuk navigasi ke Page2.xaml.
private void hlNavigate_Click(object sender, RoutedEventArgs e) { this.NavigationService.Navigate(new Uri("/Page2.xaml", UriKind.Relative)); } 7. Pada halaman Page2.xaml tambahkan kode berikut untuk menyimpan nilai kedalam state.
private void SaveOrUpdate() { Person p = null; if (PhoneApplicationService.Current.State.ContainsKey("P erson")) http://actual-training.com
15
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
{ p = (Person)PhoneApplicationService.Current.State["P erson"]; p.FirstName = txtFirst.Text; p.LastName = txtLast.Text; p.City = txtCity.Text; } else { p = new Person(); p.FirstName = txtFirst.Text; p.LastName = txtLast.Text; p.City = txtCity.Text; } PhoneApplicationService.Current.State["Person"] = p; } protected override void OnNavigatedTo(System.Windows.Navigat ion.NavigationEventArgs e) { if (PhoneApplicationService.Current.State.ContainsKey("P erson")) { Person p = (Person)PhoneApplicationService.Current.S tate["Person"]; txtFirst.Text = p.FirstName; txtLast.Text = p.LastName; txtCity.Text = p.City; } base.OnNavigatedTo(e); } private void txt_GotFocus(object sender, RoutedEventArgs e) { TextBox txt = sender as TextBox; txt.SelectAll(); } private void btnSave_Click(object sender, RoutedEventArgs e) { SaveOrUpdate(); this.NavigationService.GoBack(); }
http://actual-training.com
16
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT Displaying List of Data & Data Binding Pada contoh aplikasi dibawah ini akan ditunjukan penggunaan komponen ListBox untuk menampilkan data lebih dari satu dan mekanisme data binding pada WP7. 1. Buat Windows Phone Application dengan nama ‘SampleBinding’. 2. Tambahkan folder Images pada solution explorer, kemudian tambahkan beberapa image yang akan digunakan.
3. Tambahkan class dengan nama SampleUser.cs untuk representasi data yang akan ditampilkan.
public class SampleUser { public string UserName { get; set; } public string Message { get; set; } public string ImageSource { get; set; } } 4. Kemudian tambahkan kode berikut pada file MainPage.xaml untuk menampilkan data pada ListBox.
5. Pada event Load di halaman MainPage.xaml.cs tambahkan kode berikut untuk mengisi sample data yang akan ditampilkan di ListBox
private void PhoneApplicationPage_Loaded(object sender, Routed EventArgs e) { List<SampleUser> lstUser = new List<SampleUser>(); lstUser.Add(new SampleUser { UserName = "Erick", Message = "A Silverlight application is made up of pages that contain elements" , ImageSource = "Images/pic1.png" }); lstUser.Add(new SampleUser { UserName = "Reza", Message = "These have properties that determine where they are, how they appear
http://actual-training.com
17
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
and what they can do in an application", ImageSource = "Images/pic2.pn g" }); lstUser.Add(new SampleUser { UserName = "Rully", Message = "The Visual Studio tool allows us to manipulate the page content by u sing the design surface and the element properties pane", ImageSource = "Images/pic1.png" }); lstUser.Add(new SampleUser { UserName = "Firstman", Messag e = "The Visual Studio tool allows us to manipulate the page content b y using the design surface and the element properties pane", ImageSour ce = "Images/pic2.png" }); lstMessage.ItemsSource = lstUser; } 6. Modifikasi tampilan ListBox sebagai berikut
<StackPanel Orientation="Horizontal"> <StackPanel Width="350"> 7. Tambahkan halaman Page2.xaml. 8. Klik pada ListBox kemudian tambahkan kode berikut pada event SelectionChanged.
private void lstMessage_SelectionChanged(object sender, Select ionChangedEventArgs e) { SampleUser listItem = (sender as ListBox).SelectedItem as SampleUser; string url = string.Format("/Page2.xaml?UserName={0}", lis tItem.UserName); NavigationService.Navigate(new Uri(url, UriKind.Relative)) ; http://actual-training.com
18
Erick Kurniawan, M.Kom, MCTS, MCPD, MCT
} 9. Tambahkan juga kode untuk mengambil nilai Query String pada Page2.xaml.cs
public Page2() { InitializeComponent(); this.Loaded += new RoutedEventHandler(Page2_Loaded); } void Page2_Loaded(object sender, RoutedEventArgs e) { tbMessage.Text = NavigationContext.QueryString["UserName"]; }
19
http://actual-training.com