3. Writing Your First Windows Phone Code
In this section, we will be
writing C# code that will handle the button click event that will
populate the TextBlock named "textBlock1" with "hello World!"
To add behavior to the OK button, double-click the OK button on the Design surface of your project. Visual Studio will display MainPage.xaml.cs where you can see the btnOk_Click method is automatically added. You will add proper code in the next step to handle the button click event.
using System.Windows;
using Microsoft.Phone.Controls;
namespace HelloWorld
{
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
// Setting SupportOrientations will control the behavior
// of the page responding properly to the rotation of the
// phone. So if you rotate the phone to the landscape
// your page will change to landscape view.
SupportedOrientations = SupportedPageOrientation.PortraitOrLandscape
;
}
private void btnOk_Click(object sender, RoutedEventArgs e)
{
}
}
}
In MainPage.xaml you will notice that the button Click event handler is automatically added to OK button.
<Button Content="OK" Height="70"
HorizontalAlignment="Right" Margin="0,155,-4,0"
Name="button1" VerticalAlignment="Top" Width="160" Click="button1_Click" />
In MainPage.xaml.cs replace the button1_click method with the following code.
private void button1_Click(object sender, RoutedEventArgs e)
{
txtMessage.Text = "Hello World!";
}
4. Running Your First Silverlight Windows Phone Application
Your Hello World application is complete. Now it's time to build the application and run it in the Windows Phone 7 emulator.
To build the solution, select Build => Build Solution on the Visual Studio menu.
To run the application, select Debug => Start Debugging.
When the emulator appears, click OK and you will see "Hello World!" as shown in Figure 7.
Click the rotate control on the Windows Phone 7 emulator, as shown in Figure 8.
Notice in the landscape
view that the TextBox is automatically resized, stretched out to make
full use of the landscape orientation of the device, as shown in Figure 9.
Stop the application debugging by selecting Debug => Stop Debugging.
The Windows Phone 7 emulator
can take a long time to start, so you want to avoid closing it down
whenever possible. If you need to stop an application in the middle of a
debugging run, it's better to use the Visual Studio Debug =>
Stop Debugging command instead of completely closing down the Windows
Phone 7 emulator. Using this technique, the next time the application
debugging starts, the project will be loaded into the emulator without
first waiting for the emulator to be started. |