Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Building a Mobile Cross-Platform App from a Shared C# Code Base with UI for Xamarin

DZone's Guide to

Building a Mobile Cross-Platform App from a Shared C# Code Base with UI for Xamarin

·
Free Resource
Telerik UI for Xamarin is our latest product for cross-platform mobile apps development. It is built on top of the Telerik native controls for iOS and Android to offer Xamarin users truly native UI for their apps with no-compromise customization, flexibility capabilities and native-quality performance. The product ships Xamarin wrappers for UI for iOS, Xamarin wrappers for UI for Android and Xamarin.Forms controls.

Today, I will demonstrate how you can easily set up the Telerik Chart using a single shared codebase for the UI and for the view-model, making it work for all three platforms (iOS, Android and Windows Phone) thanks to the Xamarin.Forms support that Telerik UI for Xamarin offers. Throughout the process of building the app, you will see how to add series, load data and use annotations. This is what we are after:

Telerik UI for Xamarin - iOS View Telerik UI for Xamarin - Windows Phone View Telerik UI for Xamarin - Android View

Solution Structure

Create a Blank App (Xamarin.Forms Portable) project. Let’s call it GStartedTelerikXamarin:

Telerik UI for Xamarin - New Project

This will actually create the following projects:
  • Portable/Shared: A cross-platform application library that contains the shared code, being UI or view-models.
  • Android: A platform-specific project for the execution of the application. Available on all operation systems.
  • WinPhone: A platform-specific project for the execution of the application. Available only for projects created with Visual Studio.
  • iOS: A platform-specific project for the execution of the application. To the app to run and be debugged, we need a Mac.
Telerik UI for Xamarin - Solution Architecture


Getting the Latest Platform SDK Versions

Before diving into Telerik related stuff, let’s make sure that we have updated to what’s latest and greatest regarding Xamarin itself, and that all platform targets are correct:
  1. Right-click the GStartedTelerikXamarin solution and choose “Manage NuGet packages.”
  2. From Updates >> nuget.org install the latest version of Xamarin.Forms and Xamarin Support Library. You will be asked to restart Visual Studio afterward.
    Telerik UI for Xamarin - NuGet for AppCompat and Xamarin.Forms
  3. Right-click the GStartedTelerikXamarin.Android project and choose Manager NuGet packages. Get the Xamarin Support Library v7 AppCompat package:
    Telerik UI for Xamarin - NuGet for AppCompat-v7
  4. Right-click the GStartedTelerikXamarin solution and choose Properties >> Configuration Properties. For the GStartedTelerikXamarin.iOS Platform, choose iPhoneSimulator if you intend to test the iOS app on the simulator.
  5. In order to make the application look good for iPhone5/s screens, let’s include a 640x1136 image named Default-568@2x.png. We should set this from the project properties in Visual Studio. From the project properties, select the iOS Application tab and scroll to the Launch Images section as shown below. Click the Retina Display box to browse for your Default-568@2x.png image: Telerik UI for Xamarin - Select Retina Image
  6. You may also need to set the Deployment Target of the .iOS project’s Info.plist: Telerik UI for Xamarin - Deployment Target

Adding Telerik References

Now comes the Telerik project setup. In order to be able to work with Telerik UI for Xamarin, we should add references to the following assemblies:
  • For the Portable project    
    • Telerik.XamarinForms.Chart.dll
    • Telerik.XamarinForms.Common.dll
  • Android    
    • Telerik.Xamarin.Android.Chart.dll
    • Telerik.Xamarin.Android.Common.dll
    • Telerik.Xamarin.Android.Primitives.dll
    • Telerik.XamarinForms.Chart.dll
    • Telerik.XamarinForms.ChartRenderer.Android.dll
    • Telerik.XamarinForms.Common.dll
  • iOS    
    • Telerik.Xamarin.iOS.dll
    • Telerik.XamarinForms.Chart.dll
    • Telerik.XamarinForms.ChartRenderer.iOS.dll
    • Telerik.XamarinForms.Common.dll
  • WinPhone    
    • Telerik.Windows.Controls.Chart.dll
    • Telerik.Windows.Controls.Primitives.dll
    • Telerik.Windows.Core.dll
    • Telerik.XamarinForms.Chart.dll
    • Telerik.XamarinForms.ChartRenderer.WinPhone.dll
    • Telerik.XamarinForms.Common.dll
In addition, we should add the following code to the specified project files:

Android - MainActivity.cs
[assembly: Xamarin.Forms.ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadCartesianChart), typeof(Telerik.XamarinForms.AndroidChartRenderer.CartesianChartRenderer))]
[assembly: Xamarin.Forms.ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadPieChart), typeof(Telerik.XamarinForms.AndroidChartRenderer.PieChartRenderer))]
iOS - AppDelegate.cs

[assembly: Xamarin.Forms.ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadCartesianChart), typeof(Telerik.XamarinForms.ChartRenderer.iOS.CartesianChartRenderer))]
[assembly: Xamarin.Forms.ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadPieChart), typeof(Telerik.XamarinForms.ChartRenderer.iOS.PieChartRenderer))]
You also have to create the following instances in the beginning of the FinishedLaunching() method:

new Telerik.XamarinForms.ChartRenderer.iOS.PieChartRenderer();
new Telerik.XamarinForms.ChartRenderer.iOS.CartesianChartRenderer();
WinPhone - MainPage.xaml.cs
[assembly: Xamarin.Forms.ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadCartesianChart), typeof(Telerik.XamarinForms.ChartRenderer.WinPhone.CartesianChartRenderer))]
[assembly: Xamarin.Forms.ExportRenderer(typeof(Telerik.XamarinForms.Chart.RadPieChart), typeof(Telerik.XamarinForms.ChartRenderer.WinPhone.PieChartRenderer))]

Preparing the Data

Let’s first prepare the data. As I implied earlier, the view-model code base is common for Chart, regardless of the mobile platform it runs on. For the purposes of our demo, let’s have a list with categorical data:
public class CategoricalData
{
    public object Category
    {
        get;
        set;
    }
 
    public double Value
    {
        get;
        set;
    }
}

class MainViewModel
{
    private static string[] Categories = new string[] { "Greenings", "Perfecto", "NearBy", "Family", "Fresh" };
 
    public static List<CategoricalData> GetCategoricalData()
    {
        List<CategoricalData> data = new List<CategoricalData>();
        data.Add(new CategoricalData() { Value = 55, Category = Categories[0] });
        data.Add(new CategoricalData() { Value = 30, Category = Categories[1] });
        data.Add(new CategoricalData() { Value = 120, Category = Categories[2] });
        data.Add(new CategoricalData() { Value = 80, Category = Categories[3] });
        data.Add(new CategoricalData() { Value = 44, Category = Categories[4] });
 
        return data;
    }
}

Setting Up a New Page

  1. Let’s create the page the Chart will reside in. Right-click on the Portable Class Library project > Add > New Item... > choose Forms Xaml Page. Let’s call it MainPage.
  2. Modify the GetMainPage() method in the App.xaml.cs file to set the newly created page as a front page of the application. 
    public class App
    {
        public static Page GetMainPage()
        {
            return new MainPage();
        }
    }
  3. Set up the page background color as shown below.
    BackgroundColor = Xamarin.Forms.Device.OnPlatform(Xamarin.Forms.Color.White, Xamarin.Forms.Color.White, Xamarin.Forms.Color.Transparent);             

We can now set up the Chart in XAML, or we can do it in the code behind. Let’s see how we can do this in the code behind below.

Setting up Telerik Chart for Xamarin

Axes and Series

In the code behind of the MainPage, using the Telerik.XamarinForms.Chart namespace, create a RadCartesianChart instance and add a categorical axis making it the horizontal axis, and a numerical axis making it the vertical axis. Add a Bar series, and set the content of the page to be the Chart:

var chart = new RadCartesianChart
{
    HorizontalAxis = new Telerik.XamarinForms.Chart.CategoricalAxis()
    {
        LabelFitMode = AxisLabelFitMode.MultiLine,
    },
    VerticalAxis = new Telerik.XamarinForms.Chart.NumericalAxis()
    {
        LabelFitMode = AxisLabelFitMode.MultiLine,
        RangeExtendDirection = NumericalAxisRangeExtendDirection.Both,
        MajorStep = 30,
    },
};
 
var series = new BarSeries();
chart.Series.Add(series);
 
this.Content = chart;
 

Populating with Data

What this chart would be without data? Let’s fill it with the sample data we created in the view-model:

series.ValueBinding = new Telerik.XamarinForms.Chart.PropertyNameDataPointBinding
{
    PropertyName = "Value"
};
 
series.CategoryBinding = new Telerik.XamarinForms.Chart.PropertyNameDataPointBinding
{
    PropertyName = "Category"
};
 
series.ItemsSource = MainViewModel.GetCategoricalData();

Grid

One could get better interpretation for data if its shown on a grid background, so let’s add a grid using the Xamarin.Forms namespace:

var grid = new CartesianChartGrid();
 
grid.MajorLinesVisibility = GridLineVisibility.Y;
grid.MajorYLineDashArray = Device.OnPlatform(null, new double[] { 4, 2 }, new double[] { 4, 2 });
grid.StripLinesVisibility = GridLineVisibility.Y;
 
grid.YStripeColor = Color.FromRgba(99, 99, 99, 100);
grid.YStripeAlternativeColor = Color.FromRgba(169, 169, 169, 31);
grid.MajorLineColor = Color.FromRgb(211, 211, 211);
grid.MajorLineThickness = Device.OnPlatform(0.5, 2, 2);
 
chart.Grid = grid;

Annotations

For pointing out specific metrics that the chart gives, we can use band and line annotations. In this case, let’s take the data average and display it on the chart:

var treshold = MainViewModel.GetCategoricalData().Average(c => c.Value);
var startTreshold = treshold * 0.95;
var endTreshold = treshold * 1.05;
 
var lineAnnotation = new CartesianGridLineAnnotation()
{
    Axis = chart.VerticalAxis,
    Value = treshold,
    Stroke = Color.FromRgb(255, 0,0),
    StrokeThickness = Device.OnPlatform(0.5, 2, 2),
    DashArray = new double[] { 4, 2 },
 
};
 
var bandAnnotation = new CartesianPlotBandAnnotation()
{
    Axis = chart.VerticalAxis,
    From = startTreshold,
    To = endTreshold,
    Fill = Color.FromRgba(255, 0, 0, 50),
    StrokeThickness = 2,
    Stroke = Color.Transparent,
};
 
chart.Annotations.Add(bandAnnotation);
chart.Annotations.Add(lineAnnotation);

This is it! You can download demo project from Github. Note, that it needs the UI for Xamarin product to run. 

You can download UI for Xamarin from here , if you haven’t done so already. In the UI for Xamarin package, you will find a complimentary demo project with many examples demonstrating the Telerik Chart for Xamarin.

Happy coding!
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}