3/21/2015
Build crossplatform apps with Xamarin in Visual Studio
Build cross‐platform apps with Xamarin in Visual Studio Now, you can use C# to build native apps that run on iOS, Android, Windows, and Windows Phone. To learn more, see Xamarin Apps in Visual Studio. This guide will help you build a basic app for Android and the Windows Phone. The app will look like this.
On your way to building it, you’ll do these things. Prepare your solution to build apps for Android and the Windows Phone Run both apps in an emulator to make sure that they work Write code that you can share between the apps Design the look and feel of the Android app Design the look and feel of the Windows Phone app Take the next step If you’re ready to go, let’s start.
First, set up your solution Create an Android, Windows Phone, and a shared project, and then make a few tweaks to the solution.
Create an Android project 1. In Visual Studio, create a new Blank App ﴾Android﴿ project and name it WeatherApp. You can find this template under Visual C#‐>Android in the New Project dialog box. If you haven’t yet installed Xamarin for Visual Studio 2015 Preview, choose the Build native Android apps in C# template and follow the instructions to install it. 2. In the Control Panel, Open Programs and Features, choose the Xamarin item, and then choose the Change button.
3. In the setup wizard for Xamarin, choose the Next button, and then choose the Change button. 4. In the list of optional features to install, choose the icon next to Xamarin for Visual Studio 2015, and then choose Will be installed on local drive.
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
1/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio
After you’ve installed Xamarin, the Blank App ﴾Android﴿ project template will appear in the Android section of templates.
Create a Windows Phone project Add a Blank App ﴾Windows Phone﴿ project to the solution and name it WeatherApp﴾WinPhone﴿. You can find this template under Visual C#‐>Store Apps‐>Windows Phone Apps in the New Project dialog box.
Create a shared project 1. Add a Shared Project project to the solution and name it Shared. You can find this template under Visual C# in the New Project dialog box. If it’s not there, then download and install the Shared Project Reference Manager. 2. Open the shortcut menu for the WeatherApp project, and then choose Add‐> Reference. 3. In the dialog box that appears, select the Shared project, and then choose the OK button.
4. Repeat this process for the Windows Phone project.
Perform some minor tweaks to the solution 1. Open the Project Designer for the WeatherApp project. You can do this by opening the shortcut menu for the WeatherApp project, and then choosing Properties. 2. Choose the Application tab, and then in the Compile using Android version drop‐down list, select API Level 19 ﴾Xamarin.Android v4.4 Support﴿. 3. Close the Project Designer. 4. Open the Manage NuGet Packages dialog box and add the Newtonsoft.Json NuGet package to your solution. You’ll use classes in this package to process information that you’ll retrieve from a weather service. 5. Open the shortcut menu for the WeatherApp project, and then choose Add‐> Reference. 6. In the Reference Manager dialog box, add a reference to the Microsoft.CSharp assembly.
Run your apps to make sure that they work You’ve configured the solution. Now you’re ready to run your apps and make sure that they work.
Run the Android app 1. Open the Project Designer for the WeatherApp project. 2. Choose the Android Options tab, and then clear the Use Fast Deployment ﴾debug mode only﴿ checkbox. This prevents errors from appearing due to a temporary bug in the Visual Studio Emulator for Android.
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
2/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio 3. Close the Project Designer. 4. In Visual Studio, choose Debug‐>Start Debugging. The Visual Studio Emulator for Android starts.
Tip As an alternative to the Visual Studio Emulator for Android, you can also try using the Xamarin Android Player. 5. Open the shortcut menu for the WeatherApp project, and then choose Set as Startup Project. 6. Press the F5 key on your keyboard to run the app in the Android emulator. The app appears in the Android emulator. The app shows a button that contains the text Hello World, Click Me!. This means that the app works. 7. Stop the debugger.
Run the Windows app 1. Open the shortcut menu for the WeatherApp﴾WinPhone﴿ project, and then choose Set as Startup Project. 2. On the Standard toolbar, select one of the emulator options.
3. Press the F5 key on your keyboard to run the app in the Windows Phone emulator. Your app runs in the emulator but you won’t see any controls because you haven’t added any yet. 4. Stop the debugger.
Write code that you can share between your apps Add code that you want to share between your apps to the Shared project. A shared project is basically a container for code that runs on both platforms. Anything you add to this project is automatically included in both the Android and the Windows Phone project. 1. Add a class to the Shared project and name it Weather. 2. Open the Weather class in the code editor and replace the class declaration with the following code: C# public class Weather { public string Title { get; set; } public string Temperature { get; set; } public string Wind { get; set; } public string Humidity { get; set; } public string Visibility { get; set; } public string Sunrise { get; set; } public string Sunset { get; set; } } You’ll use this class to store data from a weather service. 3. Add another class to the Shared project and name it DataService. 4. Open the DataService class in the code editor and add the following statements to the top of the file: C# using System.Threading.Tasks; using System.Net;
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
3/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio using System.IO; using Newtonsoft.Json; 5. Replace the class declaration with the following code: C# public class DataService { public static async Task<dynamic> getDataFromService(string queryString) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(queryString); var response = await request.GetResponseAsync().ConfigureAwait(false); var stream = response.GetResponseStream(); var streamReader = new StreamReader(stream); string responseText = streamReader.ReadToEnd(); dynamic data = JsonConvert.DeserializeObject(responseText); return data; } } This code shows one way to process JSON data from a service. 6. Add another class to the Shared project and name it Core. The name Core is arbitrary. This class is just a place to put shared business logic. In this case, logic that forms a query string by using zip code, calls the weather service, and then populates Weather class. 7. Open the Core class in the code editor and add the following statement to the top of the file: C# using System.Threading.Tasks; 8. Replace the class declaration with the following code: C# public class Core { public static async Task<Weather> GetWeather(string zipCode) { string queryString = "https://query.yahooapis.com/v1/public/yql?q=select+*+from+weather.forecast+where+location=" + zipCode + "&format=json"; dynamic results = await DataService.getDataFromService(queryString).ConfigureAwait(false); dynamic weatherOverview = results["query"]["results"]["channel"]; if ((string)weatherOverview["description"] != "Yahoo! Weather Error") { Weather weather = new Weather(); weather.Title = (string)weatherOverview["description"]; dynamic wind = weatherOverview["wind"]; weather.Temperature = (string)wind["chill"]; weather.Wind = (string)wind["speed"]; dynamic atmosphere = weatherOverview["atmosphere"]; weather.Humidity = (string)atmosphere["humidity"]; weather.Visibility = (string)atmosphere["visibility"]; dynamic astronomy = weatherOverview["astronomy"]; weather.Sunrise = (string)astronomy["sunrise"]; weather.Sunset = (string)astronomy["sunset"]; return weather; } else { return null; } } }
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
4/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio
Design for Android Design the user interface, connect it to your shared code, and then run the app.
Design the look and feel of your app 1. In Solution Explorer, expand the WeatherApp‐>Resources‐>layout folder, select the Main.axml file, and then press the ENTER key. Main.axml opens in the visual designer.
Tip There are a lot of other files in the project. Exploring them is beyond the scope of this topic, but if you want to dive into the structure of an Android project a bit more, see Part 2 Deep Dive. 2. Delete the default button that appears in the designer. 3. From the Toolbox, drag a RelativeLayout control onto the designer. You can use this control as a parent container for other controls. 4. From the Toolbox, drag a TextView control onto the RelativeLayout control. 5. In the Properties window, set these properties:
Property
Value
text
Zip Code:
id
@+id/ZipCodeLabel
layout_margin_left
10dp
textSize
20sp
Tip Notice that many properties don’t contain a drop‐down list of values that you can select. It can be difficult to guess what string value to use for any given property. For suggestions, try searching for the name of a property in the R.attr class page. Also, a quick web search often leads to a page on http://stackoverflow.com/ where others have used the same property. 6. From the Toolbox, drag a Number control onto the RelativeLayout and position it next to the Zip Code label.
7. In the Properties window, set these properties:
Property
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
Value
5/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio id
@+id/ZipCodeEdit
layout_center_vertical
true
layout_margin_left
10dp
textSize
20sp
layout_width
100sp
textColor
#9933FF
8. Choose the button next to the background property. 9. In the Framework Resources tab, choose the background_light color and then choose the OK button. 10. From the Toolbox, drag a Button onto the RelativeLayout control and position it next to the zip code edit box. 11. In the Properties window, set these properties:
Property
Value
id
@+id/GetWeatherButton
text
Get Weather
layout_margin_left
10dp
textSize
20sp
12. Select the zip code edit box. Resize it to match the height of the Get Weather button by selecting and dragging the small circle that appears beneath the edit box.
You now have enough experience to build a basic UI by using the Android designer. But you can also build a UI by adding tags directly to the .asxml file of the page. Let’s build the rest of the UI by doing that. 13. At the bottom of the designer, choose the Source tab.
14. In Source view, paste the following markup beneath the </RelativeLayout> tag. Xml <TextView android:text="Current Weather" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/ResultsTitle" android:textColor="#FFFF4D" android:visibility="visible" android:layout_marginLeft="25px" /> <TableLayout android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/ResultsTable" android:padding="10dp" android:visibility="visible"> <TableRow android:id="@+id/tableRow1"> <TextView android:text="Temp:" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="0" android:id="@+id/textView21" /> <TextView
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
6/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="1" android:id="@+id/TempText" android:text="70" android:textColor="#FFFF4D" android:layout_height="wrap_content" /> <TextView android:text="F" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="2" android:id="@+id/textView26" /> </TableRow> <TableRow android:id="@+id/tableRow2"> <TextView android:text="Wind:" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="0" android:id="@+id/textView22" /> <TextView android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="1" android:id="@+id/WindText" android:text="10" android:textColor="#FFFF4D" /> <TextView android:text="mph" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="2" android:id="@+id/textView27" android:layout_height="wrap_content" /> </TableRow> <TableRow android:id="@+id/tableRow3"> <TextView android:text="Humidity:" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="0" android:id="@+id/textView23" android:layout_width="107.0dp" /> <TextView android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="1" android:id="@+id/HumidityText" android:text="70" android:textColor="#FFFF4D" android:layout_height="wrap_content" /> <TextView android:text="%" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="2" android:id="@+id/textView28" /> </TableRow> <TableRow android:id="@+id/tableRow4"> <TextView android:text="Visibility:" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="0" android:id="@+id/textView34" /> <TextView android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="1" android:id="@+id/VisibilityText" android:text="10" android:textColor="#FFFF4D" android:layout_height="wrap_content" /> <TextView android:text="miles" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="2" android:id="@+id/textView50" /> </TableRow> <TableRow android:id="@+id/tableRow5"> <TextView android:text="Sunrise:" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="0" android:id="@+id/textView40" /> <TextView android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="1" android:id="@+id/SunriseText" android:text="7:46 am" android:textColor="#FFFF4D" />
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
7/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio </TableRow> <TableRow android:id="@+id/tableRow6"> <TextView android:text="Sunset:" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="0" android:id="@+id/textView46" /> <TextView android:textAppearance="?android:attr/textAppearanceMedium" android:layout_column="1" android:id="@+id/SunsetText" android:text="5:58 PM" android:textColor="#FFFF4D" /> </TableRow> </TableLayout> 15. Open the Design view again. Your UI should appear as follows:
16. Build the solution. This adds control IDs to the Resource.Designer.cs file so that you can refer to controls by name in code.
Consume your shared code 1. Open the MainActivity.cs file of the WeatherApp project in the code editor. 2. Add the following statement to the top of the file C# using Shared; 3. Replace the OnCreate method with this code. C# protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); Button button = FindViewById<Button>(Resource.Id.GetWeatherButton); button.Click += delegate { EditText ZipCodeEditText = FindViewById<EditText>(Resource.Id.ZipCodeEdit); Weather weather = Core.GetWeather(ZipCodeEditText.Text).Result; if (weather != null) { FindViewById<TextView>(Resource.Id.ResultsTitle).Text = weather.Title;
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
8/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio FindViewById<TextView>(Resource.Id.TempText).Text = weather.Temperature; FindViewById<TextView>(Resource.Id.WindText).Text = weather.Wind; FindViewById<TextView>(Resource.Id.VisibilityText).Text = weather.Visibility; FindViewById<TextView>(Resource.Id.HumidityText).Text = weather.Humidity; FindViewById<TextView>(Resource.Id.SunriseText).Text = weather.Sunrise; FindViewById<TextView>(Resource.Id.SunsetText).Text = weather.Sunset; button.Text = "Search Again"; } else { FindViewById<TextView>(Resource.Id.ResultsTitle).Text = "Couldn't find any results"; } }; } This code calls the GetWeather method that you defined in your shared code. Then, in the UI of the app, it shows the data that is retrieved from that method.
Run the app and see how it looks 1. In Solution Explorer, set the WeatherApp project as the startup project. 2. Start the app by pressing the F5 key. 3. In the Android emulator, type a valid United States zip code into the edit box ﴾for example: 98052﴿, and then press the Get Weather button. Weather data for that region appears in the controls.
Design for the Windows Phone Design the user interface, connect it to your shared code, and then run the app.
Design the look and feel of your app 1. In Solution Explorer, select the MainPage.xaml file of the WeatherApp﴾WinPhone﴿ project, and then press the ENTER key. The MainPage.xaml file opens in the designer. 2. From the Toolbox, drag a TextBlock onto the designer and position it near the top of the page. 3. In the Properties window, expand the Common section of properties, and set the Text property to Weather App.
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
9/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio
4. Expand the Text section, and set the font size to 40px. 5. From the Toolbox, drag a TextBlock to the designer and position it beneath the Weather App title. 6. Set the Text property to Zip Code and the font size to 20px. 7. From the Toolbox, drag a TextBox to the designer and position it beside the Zip Code label. 8. Set the Name property to ZipCodeEdit 9. Clear the Text property so that no text appears in the text box. 10. On the designer, drag the edge of the textbox to widen its size. It needs to be wide enough to show five digits. 11. In the Properties windows, expand the Brush section, and then select the Foreground property. Choose an interesting color like purple.
When users enter a zip code, the text will appear in this color. 12. From the Toolbox, drag a button to the designer and position it beside the text box. 13. In the Properties window, expand the Common section, and then set the Content property to Get Weather. 14. Set the Name property to GetWeatherButton.
15. You now have enough experience to build a basic UI by using the Windows designer. But you can also build a UI by adding tags directly to the xaml file of the page. Let’s build the rest of the UI by doing that. 16. In XAML view, paste the following markup beneath the button. XAML
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
10/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio <TextBlock x:Name="ResultsTitle" HorizontalAlignment="Left" Margin="13,130,0,0" TextWrapping="Wrap" Text="Current Weather" VerticalAlignment <StackPanel x:Name="ResultsStackPanel" HorizontalAlignment="Left" Height="198" Margin="13,223,0,0" VerticalAlignment="Top" Width <StackPanel Width="100"> <TextBlock TextWrapping="Wrap" Text="Temp:" FontSize="20" Padding="0,0,0,5"/> <TextBlock TextWrapping="Wrap" Text="Wind:" FontSize="20" Padding="0,0,0,5"/> <TextBlock TextWrapping="Wrap" Text="Humidity:" FontSize="20" Padding="0,0,0,5"/> <TextBlock TextWrapping="Wrap" Text="Visibility:" FontSize="20" Padding="0,0,0,5"/> <TextBlock TextWrapping="Wrap" Text="Sunrise:" FontSize="20" Padding="0,0,0,5"/> <TextBlock TextWrapping="Wrap" Text="Sunset:" FontSize="20" Padding="0,0,0,5"/> </StackPanel> <StackPanel Width="100"> <TextBlock x:Name="TempText" TextWrapping="Wrap" Text="70" FontSize="20" Margin="0,0,‐17,5" HorizontalAlignment="Right" <TextBlock x:Name="WindText" TextWrapping="Wrap" Text="10" FontSize="20" Margin="0,0,‐17,5" Foreground="#FFEEFB00"/> <TextBlock x:Name="HumidityText" TextWrapping="Wrap" Text="70" FontSize="20" Margin="0,0,‐17,5" Foreground="#FFF0FD00"/> <TextBlock x:Name="VisibilityText" TextWrapping="Wrap" Text="10" FontSize="20" Margin="0,0,‐17,5" Foreground="#FFE8F400 <TextBlock x:Name="SunriseText" TextWrapping="Wrap" Text="7:46 AM" FontSize="20" Margin="0,0,‐17,5" Foreground="#FFF0FD00 <TextBlock x:Name="SunsetText" TextWrapping="Wrap" Text="5:58 PM" FontSize="20" Margin="0,0,‐17,5" Foreground="#FFEDF900 </StackPanel> <StackPanel Width="100"> <TextBlock TextWrapping="Wrap" Text="F" FontSize="20" Padding="0,0,0,5"/> <TextBlock TextWrapping="Wrap" Text="mph" FontSize="20" Padding="0,0,0,5"/> <TextBlock TextWrapping="Wrap" Text="%" FontSize="20" Padding="0,0,0,5"/> <TextBlock TextWrapping="Wrap" Text="miles" FontSize="20" Padding="0,0,0,5"/> </StackPanel> </StackPanel>
In the design view, your UI should appear as follows:
Consume your shared code 1. In the designer, select the Get Weather button. 2. In the Properties window, choose the event handler button ﴾
﴿.
This icon appears in the top corner of the Properties window. 3. Next to the Click event, type GetWeatherButton_Click, and then press the ENTER key. This generates an event handler named GetWeatherButton_Click. The code editor opens and places your curser inside of the event handler code block. 4. Replace that event handler with the following code. C# private void GetWeatherButton_Click(object sender, RoutedEventArgs e) { Weather weather = Core.GetWeather(ZipCodeEdit.Text).Result;
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
11/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio if (weather != null) { ResultsTitle.Text = weather.Title; TempText.Text = weather.Temperature; WindText.Text = weather.Wind; VisibilityText.Text = weather.Visibility; HumidityText.Text = weather.Humidity; SunriseText.Text = weather.Sunrise; SunsetText.Text = weather.Sunset; GetWeatherButton.Content = "Search Again"; } else { ResultsTitle.Text = "Couldn't find any results"; } } This code calls the GetWeather method that you defined in your shared code. This is the same method that you called in your Android app. This code also shows data retrieved from that method in the UI controls of your app. 5. Add the following statement to the top of the file C# using Shared;
Run the app and see how it looks 1. In Solution Explorer, set the WeatherApp﴾WinPhone﴿ project as the startup project. 2. Start the app by pressing the F5 key. 3. In the Windows Phone emulator, type a valid United States zip code into the edit box ﴾for example: 98052﴿, and then press the Get Weather button. Weather data for that region appears in the controls.
Next steps Congratulations on building your first cross‐platform mobile app. While this topic gets you started, there’s so much more to learn. Here are a few ideas about what you can explore next on your journey to build beautiful native mobile apps by using C# and Visual Studio. Add an iOS project to the solution. Extend this sample by adding a project for iOS. To build and run that app, you’ll have to connect to a networked MAC. See Hello, iOS Add platform‐specific code in the shared project. Not all shared code has to run in both platforms. Use conditional compilation constants to isolate platform‐specific code. You can reduce the number of constants that appear in a file by creating partial classes. Factor out platform‐specific code into a separate file and then apply a compilation constant to that file. See Build universal Windows apps that target Windows and Windows Phone. Scroll to the bottom of the page for an example of how to apply constants.
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
12/13
3/21/2015
Build crossplatform apps with Xamarin in Visual Studio
Consider other ways to share your code. You can also share code by using a Portable Class Library. Learn about the differences between a Portable Class Library and a shared project and choose an approach that makes the most sense for your project. See Sharing Code Options. Design one user interface that runs on all platforms. If your UI uses common patterns such as list and detail views, consider using Xamarin.Forms to design it. Xamarin.Forms uses XAML so you can declaratively bind properties and methods to your UI. This can be very attractive if your goal is to reduce the amount of code in your UI layer. Xamarin.Forms doesn’t have a visual designer. Also, if you’re interested in targeting Windows, Xamarin.Forms doesn’t produce a Windows phone 8.1 app. It produces only a Windows 8 app. These are just a few things to consider as you weigh your options. See Xamarin.Forms.
See Also Other Resources Xamarin Developer site Windows Dev Center Swift and C# Quick Reference Poster © 2015 Microsoft
https://msdn.microsoft.com/enus/library/dn879698(v=vs.140).aspx
13/13