Quantcast
Channel: Infragistics Community
Viewing all articles
Browse latest Browse all 2374

Building Data-Bound Apps in Xamarin.Forms

$
0
0

I’m so excited to bring you this special guest post from one of our partners! Please enjoy this special cross-platform app development blog by Xamarin’s very own Nish Anil!

 

 

Developers everywhere keep telling us how awesome Infragistics’ Xamarin solution, Xamarin.Forms is!  With Xamarin alone, developers can build native iOS, Android, and Windows apps from one shared C# codebase across platforms, making it fast and easy to ship high quality apps. Then, when using Xamarin.Forms, Xamarin's toolkit for cross-platform UI, lets you create UI views entirely in C# code, or you can take advantage of Extensible Application Markup Language (XAML). XAML is a declarative XML-based markup language from Microsoft used to describe user interfaces.  Since Xamarin.Forms inherently supports data binding, you can take advantage of the MVVM (Model-View-ViewModel) architectural pattern that is widely used in technologies like WPF and Silverlight within the .NET Framework.

 

With Infragistics controls for Xamarin.Forms, you can build interactive, data-bound, high-performance data visualizations for mobile apps that today's high-demand business users require. Some of the data visualization controls include Pie Charts, Gauges, Bullet Graphs and commonly used data charts with series like Category, Financial, Stacked, etc.

 

Xamarin.Forms works great for rapid development of line-of-business applications where you have fewer UI customizations and code sharing is your utmost priority. Such enterprise apps generally have straightforward requirements, like having a few forms to capture data, a dashboard to visualize data, and few customizations for user interaction. A dashboard app with charts and forms does not require too many UI customization on every platform. For example, a PieChart is represented as a PieChart, LineChart as a LineChart, etc, regardless of what platform they’re rendered on.

 

With Xamarin.Forms, MVVM, and Infragistics controls combined, you can build interactive dashboards for iOS, Android, and Windows with maximum code shared across all platforms (up to 99%).  With a little bit of customization, such as choosing right the Color, optimizing Typography, and rendering appropriate Platform specific controls, you can make your apps visually stunning and perfect for the platform.

 

 

 

For this post, I built “WorldData” sample apps in Xamarin.Forms, using Infragistics charts to display per country data, including Demography, Life Expectancy, Health and Disease, Education, etc. 

 

Data Source

 

This app uses data from Quandl and has live data fetch using Quandl APIs, as well as from an offline CSV file included as part of the project resources. I did this to show you how you can use both mechanisms to display data in your app.

 

Get Started

 

If you're new to Xamarin.Forms, I encourage you to look at the native detailed documentation before you get started.

 

To get started with Infragistics controls, follow the instructions in their documentation and set up your Xamarin.Forms project accordingly.

 

Source Code and Setup

 

The source code of this sample can be found in my Github repo. To compile and run the project successfully, please download and install Infragistics Xamarin.Forms, and add all the Xamarin.Forms related dlls to the libs folder.

Designing Pages in XAML

A page is the topmost visual element that occupies the entire screen and has just a single child. You can choose from five different pages –

     ContentPage

     MasterDetailPage

     NavigationPage

     TabbedPage

     CarouselPage

 

For this sample, NavigationPage is set to the topmost page that stacks other content pages and handles Navigations between them. All the other pages are of type ContentPage.

Layout

 

Layouts act as a container for views and other layouts. It contains the logic to set the position and size of child elements in Xamarin.Forms apps. I've used the Grid layoutsystem throughout the pages of this sample. Grid layout in Xamarin.Forms is very similar to the WPF Grid layout system; it incorporates views arranged in rows and columns.

Here's an example of a Grid written in XAML:

 

  <Grid HorizontalOptions="FillAndExpand"

          Padding="0"

          RowSpacing="0"

          ColumnSpacing="0"

          VerticalOptions="FillAndExpand">

    <Grid.RowDefinitions>

      <RowDefinition Height="300"></RowDefinition>

  <RowDefinition Height="Auto"></RowDefinition>

    </Grid.RowDefinitions>

    <Grid.ColumnDefinitions>

      <ColumnDefinition Width="*"></ColumnDefinition>

    </Grid.ColumnDefinitions>

    <Label Grid.Row="0" Grid.Column="0"></Label>

    </Grid>

 

In the above code, the Label is placed in the 1st row, 1st Column of the Grid that defines 2 rows and 1 column. To learn more about Grid, I suggest you read the Chapter - 17 Mastering the Grid of Creating Mobile Apps with Xamarin.Forms (Charles Petzold).

 

HomePage in this sample mainly consists of a PieChart representing the World Population and a searchable ListView containing the list of countries. When a country is clicked, the user navigates to the country specific details.

 

Adding a Pie Chart

 

To add an XFPieChart, first add the namespace to the Page:

xmlns:igc="clr-namespace:Infragistics.XF;assembly=InfragisticsXF"

 

then, place them in the layout

 

        <ig:XFPieChart x:Name="pieChart"

                       HeightRequest="250"

                       InnerExtent="0"

                       RadiusFactor="0.7"

                       AllowSliceSelection="True"

StartAngle="150"

                       AllowSliceExplosion="True"

                       ItemsSource="{Binding Data}"

                       LabelMemberPath="Label"

                       ValueMemberPath="Level"

                       HorizontalOptions="FillAndExpand"

                       VerticalOptions="FillAndExpand"

                       OthersCategoryThreshold="0"

                       LabelsPosition="OutsideEnd"

                       LeaderLineType="Arc"

                       LeaderLineVisibility="Visible"/>

 

Notice, the ItemSource set as {Binding Data} - Data is the property of the ViewModel that is set to the BindingContext of the View.

 

private HomePageViewModel vm;

        public HomePage()

        {

            InitializeComponent();

            BindingContext = vm =  new    HomePageViewModel();

}

 

Here's the code that loads the data country-wise and sets appropriate properties in the ViewModel.

 

worldRepository.GetCountries().ContinueWith(list =>

            {

                Countries = list.Result;

                var dataItems = new ObservableCollection<DataItem>();

                foreach (var region in worldRepository.CountriesByRegion)

                {

                    var dataItem = new DataItem {Label = region.Key, Level = region.Value.Sum(x => x.Level.ToDouble())};

                    dataItems.Add(dataItem);

                }

 

                Data = dataItems;

            });

 

In the above code, when the Data is set, the Infragistics chart automatically renders them beautifully. Similarly, the ViewModel has an ItemSource property that is used to bind the ListView data, which is also fetched from the CSV file. When the items in the ListView is tapped, the user is navigated to the CountryInfoPage.

 

Customizing the Chart

By default, the chart sets some automatic colors for the Brushes and Outline. Also, the fonts are chosen automatically. You can always customize the Colors and Typography to meet the theme of your dashboard with few lines of codes; minor tweaks can give your apps a stunning look and feel, making them stand out.

 

To change the colors of the chart, first add the BrushCollection to the ResourceDictionary

 

<ContentPage.Resources>

    <ResourceDictionary>

      <igc:BrushCollection x:Key="SliceBrushes">

        <igc:SolidColorBrush Color="#4DB6AC" />

   .....

      </igc:BrushCollection>

      <igc:BrushCollection x:Key="OutlineBrushes">

        <igc:SolidColorBrush Color="#4DB6AC" />

        <igc:SolidColorBrush Color="#4DD0E1" />

  ....

      </igc:BrushCollection>

    </ResourceDictionary>

  </ContentPage.Resources>

 

And then add them and set them to the Chart properties

<ig:XFPieChart x:Name="pieChart"

                       Brushes="{StaticResource SliceBrushes}"

                       Outlines="{StaticResource OutlineBrushes}"

....

 

Similarly, you can set the fonts according to the app theme using the FontFamily and FontSize property.

 

FontFamily="{x:Static local:Theme.FontFamilyMedium}"

                       FontSize="{x:Static local:Theme.FontSizeMicro}"

 

 

 

Connecting to Quandl Backend

 

CountryInfoPage and CountryDetailsPage for this sample connects to Quandl API for live data. Here’s the method that connects to Quandl API using HttpClient libraries and deserializes the JSON data to a model object using Newtonsoft JSON libraries.


        public async static Task<QuandlData> GetQuandlDataAsync(string authToken, string countryCode, string indicator, string transformation = null, string collapse = null)

        {

 

            //…

 

            HttpClient client = new HttpClient();

            var result = await client.GetStringAsync(uri);

 

            var data = JsonConvert.DeserializeObject<QuandlData>(result);

 

            return data;

        }

 

The above data is represented in a Infragistics LineChart in ChartView class.


 

Customizing for Each Platform

 

While Xamarin.Forms lets you build apps for iOS, Android, and Windows without writing any platform-specific code, you can make your app stand out in every platform with a few controls customizations. There are multiple ways you can customize your controls: from simple customizations, like Typography, or render a completely different control on every platform.

 

Simpler Platform tweaks

For simpler platform-specific tweaks, such as Typography, Colors, and layout changes, the Device<T> class helps in detecting and writing platform logic in your shared code. Specifically, with Device.OnPlatform generic method, you can customize simple things like Fonts.

 

public static string FontFamilyRegular

        {

            get

            {

                return Device.OnPlatform(iOS: "AvenirNext-Regular", Android: "Roboto Light", WinPhone: "Segoe WP Light");

            }

        }

 

Since the above code is written in the Theme class, you can reference them in XAML like this:

 

 <Label Text="Countries"  FontFamily="{x:Static local:Theme.FontFamilyRegular}" />

 

You can also write the OnPlatform completely in XAML resource dictionary and re-use them in your controls. Refer the documentation for details.

 

Customizing Controls using Custom Renderers

 

Since Xamarin.Forms renders fully native controls, you can always customize existing renderers, or create a new control in your shared code to write appropriate native renderers in platform-specific code.

 

For this sample app, I needed a filter control that had various options that, when selected, filtered the data and rendered the chart accordingly. Since, iOS had a UISegmentedControl that best suited my requirement, I had to find something similar for Android and Windows. Luckily, there is a PopupMenu in Android which can be used to mimic the iOS functionality.  So, I wrote a Options Control in my shared code, and wrote appropriate renderers in the platform projects. You can refer my code on GitHub repo for details:

     Options Custom Control

     OptionsRenderer - iOS (Renders UISegmentedControl)

     OptionsRenderer - Android(Renders PopupMenu Control)

 

Finally, here’s how they look in iOS and Android:

 

 

 

Custom renderers are explained in detail in the developer documentation.

 

I encourage you to dive into Xamarin.Forms and Infragistics to make your data-heavy apps visually stunning, while retaining fast development speed, native quality, and high performance[1] !

 

To learn more about Xamarin.Forms:

     Explore Xamarin’s Developer Documentation

     Download your free copy of Charles Petzold’s book, Creating Mobile Apps with Xamarin.Forms.

     Get this sample app’s source code from my Github repo, which includes a handful of reusable code snippets to apply in your projects.

 

Have a question? Find me on twitter or email me nish@xamarin.com

 

 

 

 


Viewing all articles
Browse latest Browse all 2374

Trending Articles