Xamarin Forms Cheat sheet

Post date: Mar 31, 2017 3:40:58 AM

Introduction:

Xamarin.Forms.Core + Xamarin.Forms.xaml -> implements Xamarin.Forms API

Xamarin.Forms.Platform

Core uses one of the below framework to render the UI

Xamarin.Forms.Platform.Android / Xamarin.Forms.Platform.iOS / Xamarin.Forms.Platform.WP8

Visual Elements:

Page

Content Page

Layout

Stack Layout

Grid

View:

INotifyPropertyChanged Implementation:

public class WeatherXAMLPageViewModel : INotifyPropertyChanged

    {

        //For INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged([CallerMemberName] string propertyName = "")

        {

            if( PropertyChanged != null)

            {

                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

            }

        }

}

List Implementation in XAML

<ListView x:Name="listcourses" HasUnevenRows="true" >

            <ListView.ItemTemplate>

                <DataTemplate>

                    <ImageCell ImageSource="{Binding ImageUrl}" Text="{Binding CourseTitle}" Detail="{Binding Author}" TextColor="Green" DetailColor="Orange"/>

                </DataTemplate>

            </ListView.ItemTemplate>

        </ListView>

(OR)

<ListView x:Name="listCourses" HasUnevenRows="True">

            <ListView.ItemTemplate>

                <DataTemplate>

                    <ViewCell>

                        <ViewCell.View>

                            <StackLayout Orientation="Horizontal" Spacing="20">

                                <Image Source="{Binding ImageUrl}" WidthRequest="100" HeightRequest="100" />

                                <StackLayout>

                                    <Label Text="{Binding CourseTitle}" TextColor="Pink" FontSize="24" />

                                    <Label Text="{Binding Author}" TextColor="Green" FontSize="18" />

                                </StackLayout>

                            </StackLayout>

                        </ViewCell.View>

                    </ViewCell>

                </DataTemplate>

            </ListView.ItemTemplate>

        </ListView>

Code behind implementation:

istcourses.ItemsSource = PluralsightCourse.GetCourses();

Access web services:

Newtonsoft.json

HttpClient 

HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(url);

            var response = await client.GetAsync(client.BaseAddress);

            response.EnsureSuccessStatusCode();

            var jsonResult = response.Content.ReadAsStringAsync().Result;

            var weather = JsonConver

Custom Rendering:

MyEntry is custom rendering;

Xamarin.Forms

 public class MyEntry : Entry

    {

    }

 

<?xml version="1.0" encoding="utf-8" ?>

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"

             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"

             xmlns:local="clr-namespace:CustomRenderersDemo; assembly=CustomRenderersDemo"

             x:Class="CustomRenderersDemo.CustomXAMLPage">

    <ContentPage.Content>

        <StackLayout>

            <Label Text="Custom Renderer Demo on Entry" />

            <local:MyEntry  Text="This is my Entry Control"/>

        </StackLayout>

    </ContentPage.Content>

</ContentPage>

Android:

[assembly: ExportRenderer(typeof(MyEntry), typeof(MyEntryRenderer))]

namespace CustomRenderersDemo.Droid

{

    class MyEntryRenderer : EntryRenderer

    {

        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)

        {

            base.OnElementChanged(e);

            if (Control != null)

            {

                Control.SetBackgroundColor(global::Android.Graphics.Color.LightGreen);

            }

        }

    }

}

Dependency services

Performing Platform Specific Tasks using Xamarin.Forms :

   public interface IPhoto

    {

        void TakePhoto();

    }

 

 private void Button_Clicked(object sender, EventArgs e)

        {

            IPhoto photo = DependencyService.Get<IPhoto>();

            photo.TakePhoto();

        }

Android:

  [assembly: Dependency(typeof(TakeAPhoto.Droid.MainActivity))]

namespace TakeAPhoto.Droid

{

    [Activity(Label = "TakeAPhoto", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]

    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity , IPhoto

    {

        

        public void TakePhoto()

        {

            var activity = Forms.Context as Activity;

            var picker = new MediaPicker(activity);

            var intent = picker.GetTakePhotoUI(new StoreCameraMediaOptions

            {

                Name = $"pic-{Guid.NewGuid()}.jpg",

                Directory = "Sekhar"

            });

            activity.StartActivityForResult(intent, 1);

        }

    }

}

 

iOS:

[assembly:Dependency(typeof(TakeAPhoto.iOS.Photo_iOS))]

namespace TakeAPhoto.iOS

{

    public class Photo_iOS : IPhoto

    {

        public async void TakePhoto()

        {

            var picker = new MediaPicker();

            var mediaFile = await picker.PickPhotoAsync();

            MessagingCenter.Send<IPhoto, string>(this, "pictureTaken", mediaFile.Path);

        }

    }