Click here to Skip to main content
14,305,260 members

Xamarin Questions & Answers

Rate this:
5.00 (2 votes)
Please Sign up or sign in to vote.
5.00 (2 votes)
28 Apr 2018CPOL
This article contains possible basic questions along with their answers to help you to understand or gain basic knowledge about Xamarin.

Disclaimer

This article contains a list of possible basic questions related to Xamarin technology along with answers. This will help you to refresh your knowledge or get a basic knowledge about it. This considers that you have developed few apps using Xamarin and strictly assumes that you have a practical knowledge of Xamarin and related technology aspects.

Introduction to Xamarin

Xamarin is a Cross Platform Mobile Development technology by Microsoft where we can develop the native app using the same code base across all platforms (iOS, Android, UWP) using the C# language. Xamarin uses two approaches for the app development, Xamarin.Forms and Xamarin Native. Xamarin.Forms uses MVVM & XAML while Xamarin Native uses native UI technology and MVC or MVVMCross Architecture.

So, now let's jump over to the questions!!

Difference between Xamarin.Forms & Xamarin Native

Xamarin.Forms is used when:

  • Less platform-specific code is required
  • Code sharing is more important than custom UI
  • UI is not complex

Xamarin Native is used when:

  • Lot of platform specific code is required
  • Custom UI is more important then code sharing
  • Many platform-specific APIs are used

What is Xamarin.Forms and what are the benefits of using it?

Xamarin.Forms is a CrossPlatform Toolkit which helps share Business Logic as well as UI using XAML across all supported platforms.

It uses MVVM pattern along with Binding into the XAML UI to accomplish this. It produces pure native controls for each individual platforms. Using Xamarin.Forms, we can share the whole business logic as well as UI among all supporting platforms like iOS, Android and UWP. It also provides a way for platform specific customization of any native controls using Renderers. Thus, we can almost share about 80-90% of code across platforms. We can say Xamarin is the King of Cross Platforms.

Which Languages are supported for Xamarin development?

C# & F#

What is the basic architecture of Xamarin.Forms project?

Xamarin.Forms can consists of four (this varies based on requirements) projects under one solution.

  • .NET Standard, PCL or Shared Project
  • iOS Project
  • Android Project
  • UWP Project

Here, .NET Standard, PCL or Shared Project contains all UI & Business logic inside it.

iOS, Android, UWP contains platform specific code containing Renderers or Dependency Services Implementations.

How many ways can we share the code?

There are three ways we can share code:

  • Shared Project: Here, if required, we write platform specific code using #if compiler directives.
  • Portable Class Libraries: Here, we create a PCL targeting the platforms we wish to support and then we use Interfaces & Dependency Services to use platform specific functionality.
  • .NET Standard Libraries: It works similar to the PCL and requires Interfaces to work with platform specific functionality.

What is the difference between PCL & Shared Project?

  • PCL has an output assembly as DLL while Shared Project has no output assembly.
  • Files inside PCL are treated as part of PCL while in Shared Project, files are treated as part of the referencing project and compiled into that assembly.
  • PCL contains neat and clean platform independent code while Shared Project consists of many #if compiler directives to differentiate code among platforms.
  • PCL is the best approach if good project architecture is the main concern instead of Shared Project.
  • PCL uses the Interfaces and DependencyServices to access platform specific features while Shared Project can assess them directly.
  • PCL has less compile time errors while Shared Project has many chances of compile time errors while switching among platform specific projects.
  • PCL is used if less platform specific code is required. Shared Project is used when lot of platform specific code is required. However, this is not true all the time. Choice is always on the developer.

What is App.cs class?

App.cs is the main class of the app which offers features like:

  • MainPage: It helps to set the initial page for the app.
  • Properties Dictionary: It helps us store simple values across lifecycle states.
  • Static Current Property: It gives the instance of the current application object.

Explain Lifecycle methods of Xamarin.Forms app.

Lifecycle methods are set of methods which get executed when application enters into a specific state. Following are such methods:

  • OnStart: Executes when application starts from the beginning
  • OnSleep: Executes each time when application goes into the background
  • OnResume: Executes when application comes into the foreground from the Sleeping state

What is the purpose of XAML Compiler (XAMLC)?

Using XAML compiler, we can directly compile XAMLs into intermediate language (IL) optionally.

Benefits:

  • It performs compile time checking of any errors in XAML, thus notifies the user for any errors at compile time.
  • It removes some of the overhead and instantiation time for XAML elements.
  • It doesn't include the XAML files into the final assembly and thus it reduces the assembly size.

By default, it is disabled and we can enable it at assembly level as well as class level, by adding XamlCompilation attribute as follows:

Example:

Assembly Level:
using Xamarin.Forms.Xaml;
...
[assembly: XamlCompilation (XamlCompilationOptions.Compile)]
namespace XamSampleApp
{
  ...
}

Class Level
using Xamarin.Forms.Xaml;
...
[XamlCompilation (XamlCompilationOptions.Compile)]
public class HomePage : ContentPage
{
  ...
}

What is XAML namespace declaration?

XAML namespace is a declaration of the namespaces on top of the XAML file, to declare, from which namespaces that XAML will use the elements from.

There are always two declarations available within the root element, when we create any new XAML UI.

Following is the default xmlns declaration without any prefix:

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

Second is the declaration which uses the x prefix:

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

All namespace declarations which use the prefix are non-default declarations.

Suppose we want to bind the viewmodel with XAML and that viewmodel is declared inside the namespace "XamSample.ViewModels", we have to declare this namespace on top of the XAML like:

xmlns:vm="clr-namespace:XamSample.ViewModels; assembly=XamSample.ViewModels"

Then, we can access the elements from inside this namespace using the vm prefix in our XAML.

When should I declare the assembly name along with namespace declaration in XAML?

If, the types are defined in the local assembly where XAML file is declared, then there is no need to declare the assembly name. Example:

<ContentPage ... xmlns:local="clr-namespace:XamSample" ...>
  ...
</ContentPage>

But if the types are defined inside the different assembly, then the assembly name has to be provided in the namespace declaration. Example:

<ContentPage ... xmlns:behaviors="clr-namespace:Behaviors;assembly=BehaviorsLibrary" ...>
  ...
</ContentPage>

What is XAML Markup Extensions?

XAML Markup Extension helps us extend the power of providing the value to the attributes of the control from the different sources instead of just providing string literals.

Example: When we assign a color to the some control, we may write like:

<BoxView Color="Red"/> or <BoxView Color="#FF0000">

Here, we provided Color attribute, as string values, which then gets converted into "Color" class type value.

But, you may wish to set the Color attribute with the value stored in the ResourceDictionary, or from a static property of some class, or from a Color property of some another element on the same XAML page, etc.

All these options are possible, if we use XAML Markup Extensions. It is just a different way to express an attribute of an Element. Any attribute setting which is enclosed within curly braces are simply known as Markup Extensions. Example:

<BoxView Color="{StaticResource PrimaryThemeColor}" />

How many types of different XAML Markup Extensions do you know?

There are different Markup Extensions available to access from x prefix of the namespace declaration such as:

  • x:Static: Used when we want to access static properties, fields, or Enum members in XAML elements.
  • x:Reference: Used when we want to declare the reference of some named element into some other element of the same XAML Page.
  • x:Type: Used when we want to set the type of some attribute to System.Type object.
  • x:Array: Used when we want to construct the array of objects of some specific type.
  • x:Null: Used when we want to set the value of some attribute to a null.

What is ResourceDictionary?

  • ResourceDictionary is used to define the XAML Resources which can be re-used more than once throughout the Xamarin.Forms application.
  • XAML resources are the definition of objects which can be used more than once.
  • ResourceDictionary allows all such resource objects declared at one place.
  • Generally, we can define Styles, ControlTemplates, DataTemplates, Colors and Converters into the ResourceDictionary.
  • In XAML, these resources can be accessed using the StaticResource Markup Extension.
  • ResourceDictionary can be declared at either Element Level (inside specific Element), Page Level (inside Page) or Application Level (inside App.xaml).
  • For examples, click here.

How many types of Pages are available in Xamarin.Forms?

Page is generally a Visual element which occupies all or most of the screen space containing a single child.

  • Content Page: It displays a single View generally containing a ScrollView or StackLayout.
  • Master Detail Page: It manages two panes of information, generally used for Sliding Panel/Drawer.
  • Navigation Page: It manages the navigation stack of Pages.
  • Tabbed Page: Used when navigation among children pages, using Tabs, is required.
  • Templated Page: It displays full screen content with a control template.
  • Carousel Page: It allows swipe gestures between sub pages similar like Gallery.

When would you use the NavigationPage as a MainPage?

When we want the hierarchical navigation of pages like forward or backward navigation, we may instantiate a very first page (for example: MyFirstPageXaml) wrapped into a NavigationPage and then assign it, to a MainPage property of App.cs class. For example:

public App ()
{
    MainPage = new NavigationPage (new MyFirstPageXaml ());
}

This causes the MyFirstPageXaml page instance to be pushed into the navigation stack and this page becomes the active page and acts as a Root Page of the app. Thus, it creates a stack of pages which are being pushed in LIFO (Last-In-First-Out) manner. It is recommended that we pass only "ContentPage" instances into the NavigationPage.

What is the purpose of InitializeComponent() method in Page?

This method is auto-generated when we add any new XAML Page to the project. It instantiates and initializes all the objects which we have defined into the XAML file. It connects them with each other based on their parent child relations. It attaches the Event Handlers we defined in the code with the Events, we set in the XAML. Then, it generates the whole tree of objects like a content of a page.

We should never access any control of our page before this call because before this call, none of the controls get initialized or exist and so, we will get an Exception.

How will you navigate from one page to another?

On some button click event of First Page, we can call the following method, which will navigate to the second page.

await Navigation.PushAsync (new MySecondPageXaml (), true);

We have to use the "Navigation" property which is available under ContentPage class (XAML Page's code behind). So this navigation can be written in the Page's code behind file.

Can we access Navigation property in ViewModel?

Yes, like the following code:

var navigation = Application.Current.MainPage.Navigation;

So, how do we perform navigation from ViewModel?

There are two ways in which you can navigate from ViewModel:

Simple Way

Write the following in your ViewModel, where we directly access the Application's MainPage instance and access Navigation Property.

Application.Current.MainPage.Navigation.PushAsync(new MyDestinationPageXaml());

Non-Simple Way

While providing a BindingContext to a page in code-behind, you can pass Navigation property instance of your Page into ViewModel constructor and then assign this parameter to ViewModel's INavigation property.

Then, use this INavigation property instance to navigate to other pages as given in the below example:

public partial class HomeView : ContentPage
{
    public HomeView ()
    {
        InitializeComponent();
        BindingContext = new HomeViewModel(Navigation);
    }
}

ViewModel:
public class HomeViewModel
{
    public INavigation _navigation; 

    public HomeViewModel (INavigation navigation)
    {
        _navigation = navigation;
        GoToAnotherPageCommand = new Command(async () => await GoToAnotherPageCommandExecute());
    }

    //now, to navigate on some Button click Command:
    private async Task GoToAnotherPageCommandExecute()
    {
        await _navigation.PushAsync(new MyDestinationPageXaml(), true);
    }
}

Name few widely used Layout Controls

  • Frame: It contains a single element as a child having a default padding of 20.
  • Grid: It is used when UI components are to be arranged into Rows & Columns.
  • StackLayout: It is used when UI components are to be arranged either horizontally or vertically.
  • ScrollView: It enables the scrolling for a child element if required. It has one child only.

There are other Layout Controls too like AbsoluteLayout, RelativeLayout, ContentView, ContentPresenter, etc.

How many LayoutOptions do we have?

They are:

  • Start, StartAndExpand
  • Center, CenterAndExpand
  • End, EndAndExpand
  • Fill, FillAndExpand

So, what is the special meaning with "AndExpand" Suffix with each LayoutOptions?

Suppose we have some elements added into the StackLayout with any of the Expand options above, all of the child elements will try to occupy more space if available to use. If StackLayout has any unused space, then the unused space is shared equally by all the child elements which request the Expansion by using "AndExpand" suffix in the Horizontal or Vertical LayoutOptions. If all the space is used in the StackLayout, then the "AndExpand" has no effect.

What is the difference between Margin and Padding properties?

Margin property represents the distance between the element and its adjacent elements and is used to control the element's rendering position, and the rendering position of its neighbors. Margin can be specified on Layout and View classes.

Padding property represents the distance between an Element and the child elements of it and thus it is used to separate the control from its own content. Padding values can be specified on Layout classes.

Suppose, two adjacent elements have a margin of value 20 pixels assigned, what will be the distance between these two elements? Why?

The distance between two elements will be 40 pixels in this case, because, Margin property values are Additive. In addition to this, if Margin and Padding both are applied, then the distance between element and its content will be Margin + Padding.

What is the Type of Margin and Padding Properties?

The type of both of these properties is Thickness.

Thickness values can go negative, which can clip or overdraws the content.

How to add / draw a separator line between two controls?

We can use the BoxView between two controls as given in the following example:

Horizontal Separator

<StackLayout Orientation="Vertical">
    <Label Text="Title"/>
    //This is a horizontal separator line between two labels
    <BoxView HeightRequest="1" BackgroundColor="Black" HorizontalOptions="FillAndExpand" />
    <Label Text="Description"/>
</StackLayout>

Vertical Separator

<StackLayout Orientation="Horizontal">
    <Label Text="Title"/>
    <BoxView HeightRequest="100" WidthRequest="1" BackgroundColor="Black" />
    <Label Text="Description"/>
</StackLayout>

Which best practices to follow while designing the XAML Page?

  • Don't create UI in code behind. Use XAML for it because XAML is more readable then code.
  • Avoid using a RelativeLayout. It asks CPU to perform significantly more work.
  • Enable the XAML Compiler. It performs compile time checking of XAML for any errors and removes some of the load.
  • Use correct layout to achieve desired UI. Don't use StackLayout if the same can be achieved by using Grid. Grid is more lightweight then StackLayout.
  • Use Layout Compression to improve the Page rendering performance.
  • Don't use Binding when there is no need to. Example: if Button title is not dynamic, then give it statically in XAML itself.
  • Don't set the VerticalOptions and HorizontalOptions properties of a layout unless required.
  • Always try to reduce the Visual Tree Size.
  • Reduce the Application Resource Dictionary Size.

What is ViewCell and How many types of built-in Cells are available?

A ViewCell is a small individual element which re-presents a single item of the ListView or Table. A ViewCell is actually not a Visual Element, but it is a description of the template which creates a Visual Element.

List of Built-in cells:

  • TextCell: It is a cell that consists of a Title / Primary text and a Detail / Secondary text label.
  • ImageCell: It is basically a TextCell but also includes an Image component on the left.
  • SwitchCell: This cell consists of the Label and one Toggle Switch.
  • EntryCell: This cell contains a Label and single line of textbox that can be used to enter the data.

Why do we need to create a Custom ViewCell?

Built in cell actually allows us to show some data into the List for some simple scenarios. But, in some real world scenarios, these simple cells can't fulfill all our needs. For example, let's say we want to show few labels, 2 buttons, and one image to the right side of the cell. This scenario can't be accomplished using built-in cells. So, we have to go for some customization. In the ListView's DataTemplate, we can simply wrap our own set of controls in ViewCell Tag.

Example:

<ListView RowHeight="60">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal" HorizontalOptions="Fill">
                    <StackLayout Orientation="Vertical">
                        <Label Text = "{Binding Name}" />
                        <Label Text = "{Binding Email}" />
                    </StackLayout>
                    <Image Source="{Binding ProfileImage}" HorizontalOptions="End" />
                    <Button Text="Delete" WidthRequest="100" HeightRequest="50" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

How to render different types of ViewCell in the same ListView during runtime?

Xamarin.Forms implements DataTemplateSelector (introduced in Xamarin.Forms V 2.1), which provides a way to customize the presentation of a Cell at Runtime. For example, if we want to create a ListView which displays the chat messages, then we display incoming message to the Left and outgoing messages to the Right along with different colors. We can achieve this using the DataTemplateSelector.

We have to override the DataTemplateSelector class and design different DataTemplates for Incoming and Outgoing messages and then, at runtime, we can decide which one to select for the ListView item based on the bound data.

For more details, click here.

How to increase the ListView performance?

  • Do not put ListView inside ScrollView because ListView has its own Scrollview.
  • Try to use built-in cells like TextCell, EntryCell, ImageCell, SwitchCell instead of creating custom ViewCell whenever possible.
  • Reduce the usage of Cell.ForceUpdateSize method. It will degrade the performance.
  • Avoid changing the cell layout based on BindingContext.
  • Avoid deeply nested layouts. Use AbsoluteLayout or Grid.
  • Avoid Specific LayoutOptions other than Fill.
  • If your cell contains complex UI, then use custom renderers.

How to store simple Key-Value data?

Xamarin.Forms's Application class exposes the Application.Current.Properties Dictionary which is used to store the simple Key-Value pair data. The Properties dictionary uses a string key and stores an object value.

Example:

///Store Value
Application.Current.Properties ["UserId"] = loggedInUser.Id;

///Get Value
if (Application.Current.Properties.ContainsKey("UserId"))
{
    var userId = Application.Current.Properties ["UserId"] as int;
    // do something with userId
}

What is Behaviors and give some examples where we should use Behaviors?

Behaviors help us in adding functionality to user interface controls without creating a subclass of it. Required functionality is implemented using the Behavior class and attached to that control as if it is part of this control.

Examples where we can use Behaviors are:

  • An Email Validater in an Entry
  • Creating a rating control using a Tap Gesture
  • Controlling Animation
  • Adding some effect to a control

How to Bind View's event with Command?

We can use EventToCommandBehavior class to achieve this. It invokes a command when specified event is fired.

Example:

<ListView ItemsSource="{Binding Employees}">
  <ListView.Behaviors>
    <local:EventToCommandBehavior            

           EventName="ItemSelected"

           Command="{Binding OutputAgeCommand}"

           Converter="{StaticResource SelectedItemConverter}" />  
  </ListView.Behaviors>
</ListView>

Can we bind a Command on Image tap?

Yes, Xamarin.Forms provides GestureRecognizers like Tap, Pinch and Pan GestureRecognizers. We have to use a TapGestureRecognizer on Image and bind a command to it as follows:

<Image Source="profile_pic.png" Margin="25,3,25,0">
    <Image.GestureRecognizers>
        <TapGestureRecognizer Command="{Binding ProfileImageTapCommand}" NumberOfTapsRequired="1"/>
    </Image.GestureRecognizers>
</Image>

What is Custom Renderers and what is its purpose?

Custom Renderers provide an approach for customizing the look and feel & behaviors of the Xamarin.Forms controls specific to platforms. Thus it enables for us to customize any Xamarin.Forms visual elements natively. Moreover, if something is not possible with Xamarin.Forms for some visual elements, we can achieve it using Renderers.

What is Effects and When should we use it over Custom Renderers?

Using Effects, we can customize the native controls on each platforms. Same can be achieved using Custom Renderers, but sometimes it is recommended to use Effects instead of Custom Renderers.

  • Effects is recommended when there is a small style change for a control. However, using Custom Renderer can be heavy for this small change.
  • Implementing Effects is simpler and reusable rather than Custom Renderers.
  • Effects can be parametrized, to make it more reusable.

What is difference between ControlTemplate & DataTemplate?

ControlTemplate decides how a Control should look, means it defines the representation style for a Control. Example: Button can contain Image and Text.

DataTemplate decides the visual structure for underlying data, means how you would like to represent data.

What are Triggers? How many types of Triggers are available?

Triggers allow us to declare actions in XAML which changes the appearance of the control when specific condition is met for specific control property or specific event is raised.

We can add triggers to the control-level, page-level or application-level in the resource dictionary. There are four types of Triggers.

  • Property Trigger: executed when a property on a control is set to a particular value
  • Data Trigger: It is similar to the property trigger but it leverages the use of data binding
  • Event Trigger: occurs when some specified event is raised on the control
  • Multi Trigger: allows multiple trigger conditions to be set before an action occurs

For more details about Triggers, click here.

How to display static HTML string in Xamarin.Forms?

We can use WebView control to display static HTML string. WebView can be used to display Websites, HTML string, Documents, Local Files depending on the platform support.

Add WebView control in XAML as below and Bind the property which contains the HTML string with HtmlWebViewsource's Html property as shown below:

<WebView VerticalOptions="FillAndExpand" >
    <WebView.Source>
        <HtmlWebViewSource Html="{Binding HtmlString}"/>
    </WebView.Source>
</WebView>
public class MyWebViewModel : BaseViewModel
{
    public string HtmlString
    {
        get
        {
            return @"<html><body>
                        <h1>HTML in WebView</h1>
                        <p>Hello Xamarin</p>
                    </body></html>";
        }
    }
}

What is DependencyService? Describe steps for the implementation.

DependencyService is used to call the native platform specific implementation of some feature from the PCL or Shared project. Thus, it helps us in doing anything that native app can do.

Steps:

  • Interface: Define an interface for specific feature into the PCL or shared Project.
  • Implement it per Platform: Add class into the Platform specific project and implement this interface into that class by inheriting this interface to it.
  • Registration: Register each of these platform specific classes with DependencyService by providing metadata attributes to it.

Now, we can access the native implementation of this class into PCL or Shared project by DependencyService.

How do we provide Platform specific styling or values in XAML?

We can use OnPlatform Tag in XAML to achieve this. OnPlatform Tag provides a way to declare platform specific values to some properties directly into XAML.

Example: If we want to provide different font size to a Button for each platform, it can be achieved like:

Old Way:
<Button VerticalOptions="CenterAndExpand" Text="Save">
    <Button.FontSize>
        <OnPlatform x:TypeArguments="x:Double" iOS="15" Android="13" WinPhone="14" />
    </Button.FontSize>
</Button>

New Way:
<Button VerticalOptions="CenterAndExpand" Text="Save">
    <Button.FontSize>
        <OnPlatform x:TypeArguments="x:Double">
            <On Platform="iOS">15</On>
            <On Platform="Android">13</On>
            <On Platform="WinPhone">14</On>
        </OnPlatform>
    </Button.FontSize>
</Button>

How to design separate layouts or functionality between Phone & Tablets?

Xamarin.Forms provides Device.Idiom enumeration through which we can tweak the design/layout/functionality between Phone & Tablet. TargetIdiom enum provides following values to differentiate among various devices.

Phone, Tablet, Desktop, TV, Unsupported

<Grid VerticalOptions="FillAndExpand">
   <Grid.ColumnSpacing>
      <OnIdiom x:TypeArguments="x:Double" Phone="20" Tablet="40"/>
   </Grid.ColumnSpacing>  
   <Grid.Padding>
      <OnIdiom x:TypeArguments="Thickness" Phone="10, 10, 10, 0" Tablet="20, 20, 20, 0"/>
   </Grid.Padding>
  <!-- Grid Content -->
</Grid>

In Code:
if (Device.Idiom == TargetIdiom.Phone) {
    // layout views vertically
} else {
    // layout views horizontally tablet or desktop
}

How to perform Binding in Code Behind?

Every BindableObject has an extension method, called SetBinding, which takes View's bindable property and the corresponding property from the ViewModel which you want to bind to.

In the following example, I have tried to bind the Title, FirstName & LastName properties from the EmployeeViewModel to the respective BindableObject's Text property in the code behind.

EmployeeDetailPage.cs Backend:

public partial class EmployeeDetailPage : ContentPage
{
    public EmployeeDetailPage()
    {
        BindingContext = new EmployeeViewModel();
        InitializeComponent();

        //Label
        lbl_Title.SetBinding(Label.TextProperty, "Title");
        
        //Textboxes
        tb_FirstName.SetBinding(Entry.TextProperty, "FirstName", BindingMode.TwoWay);
        tb_LastName.SetBinding(Entry.TextProperty, "LastName", BindingMode.TwoWay);         
    }
}

What is View-to-View Binding?

View-to-View Binding means binding a value of one property of one control to the other control's property in the XAML file itself.

Example: If we want to rotate a Label based on the Slider value, then we can bind a "Rotation" property of Label with Slider's "Value" property as below:

For such cases, we don't have to explicitly create a ViewModel Properties and Bindings.

<StackLayout>

    <Label Text="Rotate Me"

        BindingContext="{x:Reference Name=slider}"

        Rotation="{Binding Path=Value}"

        FontSize="Large"

        HorizontalOptions="Center"

        VerticalOptions="CenterAndExpand" />

    <Slider x:Name="slider"

        Maximum="360"

        VerticalOptions="CenterAndExpand" />

    <Label BindingContext="{x:Reference slider}"

        Text="{Binding Value, StringFormat='The angle is {0:F0} degrees'}"

        FontSize="Large"

        HorizontalOptions="Center"

        VerticalOptions="CenterAndExpand" />

</StackLayout>

How many ways you can Bind a ViewModel with XAML?

We can bind a ViewModel directly into the XAML or we can bind it into XAML's backend .cs file.

When we bind a ViewModel in XAML, it is said a View-First Construction in XAML.

When we bind a ViewModel in Code behind, it is said a View-First Construction in Code behind.

Examples:

Binding ViewModel in XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 

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

             xmlns:vm="clr-namespace:XamSample.ViewModels; assembly=XamSample.ViewModels" 

             x:Class="XamSample" 

             Title="Home Page"> 
    <ContentPage.BindingContext> 
        <vm:HomeViewModel/> 
    </ContentPage.BindingContext> 
    <StackLayout> 
        <Label Text="{Binding Title}"/> 
    </StackLayout> 
</ContentPage>

Binding ViewModel in backend .cs file:
public partial class HomePage : ContentPage
{
    public HomePage()
    {
        BindingContext = new HomeViewModel();
        InitializeComponent();
    }
}

Is there any benefit in binding a ViewModel in backend .cs file?

Yes, we can customize the ViewModel initialization in the XAML's backend .cs file. Suppose, we want to initialize it with some dynamic data. So if your page requires some dynamic data passed into the page before it gets loaded, you need to pass it into ViewModel's parameterized constructor. Now assign this instance of ViewModel to the BindingContext of a Page in the backend .cs file. Thus, it helps us in constructing the ViewModel with some data.

Example:

public partial class HomePage : ContentPage
{ 
    public HomePage(int userId) 
    { 
        //Ex. I want to pass the logged in user id into HomeViewModel then,        

        BindingContext = new HomeViewModel(userId); 
        InitializeComponent(); 
    } 
}

Can we really declare Parametrized ViewModel instance as BindingContext in XAML?

Yes, but we can pass static values only. We can use x:Arguments attribute. Example:

<ContentPage.BindingContext>
    <vm:HomeViewModel>
        <x:Arguments>
            <x:Int32 >1234</x:Int32> //This is passed as a static value as an argument 
                                     //to the parametrized construction of ViewModel in XAML.
        </x:Arguments>
    </vm:HomeViewModel>
</ContentPage.BindingContext>

public class HomeViewModel : BaseViewModel
{
    //Parametrized initialization of viewmodel
    public HomeViewModel(int employeeId)
    {
         //Here you will get 1234 value in the employeeId parameter.
    }
}

This requires that the ViewModel constructor parameters matches with the Type and number of arguments provided in XAML.

How many ways we can Bind data?

There are four ways we can bind the data to the BindableObject.

  1. Default: When we use the Default Binding mode, it indicated that as OneWay binding, means, data change propagates from source (ViewModel in this case) to View element.
  2. OneWay: It reflects the change from source to View element as mentioned above. Example: Label uses OneWay binding.
  3. OneWayToSource: It reflects the changes from target (BindableObject) to source (ViewModel). This is basically used for the readonly Bindable Properties.
  4. TwoWay: It reflects the changes between source and target in both directions. Example: Entry generally uses the TwoWay binding.

What is the purpose of INotifyPropertyChanged?

It notifies the client that a value of specified property is changed. Generally, we implement this interface to the object (ViewModel) which is bound to the target UI elements.

What is MessagingCenter?

Using MessagingCenter, we can enable our ViewModels or other components of our application to communicate with each other, without knowing anything about each other. Thus it decouples senders and receivers from each other. It is just a simple messaging contract, where receiving object has to Subscribe or Unsubscribe the Message sent by the Sender.

Example: Suppose we want to edit some detail in one Page, and want to notify the other Pages about this update, then we can send Message and other Pages, which have subscribed for this Message, will receive the notification via this Message and thus we can take appropriate actions in other Pages based on it.

So, what is the difference between MessagingCenter and Events?

Events makes a strong coupling between objects, means Sender and Receiver have to know about each other. Due to this coupling, sometimes, resources doesn't get freed up from memory, and we have to unsubscribe events to free up the resources properly.

MessagingCenter decouples objects and thus there is no such dependency among objects and so they get freed up when no longer required. But using too much of MessagingCenter can make it harder for developers to understand who sent it and when they sent it, making it hard to debug the code too. So, we should use them wisely.

How to call a specific method for some specific Platform only?

We can use the Device.RuntimePlatform enumeration to check for the platform as below:

if (Device.RuntimePlatform == Device.iOS)
{
    //Call the iOS Specific Method here
}


So, that's it for now. There can be many more good questions other than these but the list can go longer. I have yet tried to cover most of the basic questions which can help you know the Xamarin basics. Still, If you have a good question in your mind which can help others know about, you can share it in the comment below. I will be happy to add them in this list.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

MilanGohil
Technical Lead
India India
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
Article
Posted 28 Apr 2018

Stats

19.2K views
5 bookmarked