Building Your First Windows Phone 7 Application (part 3) - Writing Your First Windows Phone Code
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.
Figure 7. Hello World in Windows Phone 7 Emulator
Click the rotate control on the Windows Phone 7 emulator, as shown in Figure 8.
Figure 8. Clicking Windows Phone 7 Emulator rotate control
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.
Figure 9. Hello World landscape view
Stop the application debugging by selecting Debug => Stop Debugging.