Xamarin.Forms - Create Properties Using Fody in MVVM

Introduction

Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

Fody

  • Fody is a library for IL weaving (the process to manipulate/inject code in IL). Fody will update automatically our code for us to add new cool features.
  • Fody injects code that raises the PropertyChanged event, into property setters of classes that implement INotifyPropertyChanged.

Prerequisites

  • Visual Studio 2017 or later (Windows or Mac)

Setting up a Xamarin.Forms Project

Start by creating a new Xamarin.Forms project. You will learn more by going through the steps yourself.

Create a new or existing Xamarin forms(.Net standard) Project. With Android and iOS Platform.

Setup UI

Now, Create a UI for your requirement. I just created a simple UI for LoginPage

LoginPage.XAML

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="XamarinApp.LoginPage">
    <ContentPage.Content>
        <StackLayout HorizontalOptions="Fill"  Margin="50,100" VerticalOptions="Start">
            <Label Text="Login" FontSize="Large"/>
            <Entry Placeholder="Username" Text="{Binding UserName}"/>
            <Entry Placeholder="Password" IsPassword="True" Text="{Binding Password}"/>
            <Label Text=""/>
            <Button Text="Login"/>

        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Normal Property Creation with Data Binding

The Data Binding is the connection between the XAML and ViewModel of your app. You use it to connect a control (ex: text) of your UI to your logic. Let’s assume that we have an entry and we want to link it to our ViewModel.

Following code is as we use to create the view model property be like.

LoginPage.Xaml.cs

Here, I created one Username property with added INotifyPropertyChanged for that property.

public class LoginPageViewModel: INotifyPropertyChanged
{
    #region Fields

    private string _username;

    #endregion

    #region Constructor
    public LoginPageViewModel()
    {
    }
    #endregion

    #region Properties

    public event PropertyChangedEventHandler PropertyChanged;

    public string UserName {
        get { return _username; }
        set {
            _username = value;
            OnPropertyChanged(nameof(UserName));
        }
    }
    #endregion

    #region Methods

    protected void OnPropertyChanged(string name)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
    #endregion
}

Result for normal property

See here, the breakpoint hinting the property whenever change the value in XAML element.

Install Fody

Install the following Nuget from Nuget Manager In your Visual Studio.

In your project install the Fody and PropertyChanged.Fody plugin (only in your PCL/.Net Standard project), you don’t need to install in the Android, iOS, UWP projects

  1. Fody
  2. PropertyChanged.Fody

Fody NuGet

Install following fody Nuget package from Nuget manager with the stable version

PropertyChanged.Fody NuGet

Install following PropertyChanged.Fody NuGet package from Nuget manager with the stable version.

Add FodyWeavers.xml

Now, create the FodyWeavers.xml file in your .Net Standard project and add the following code in the FodyWeavers.xml file.

?xml version="1.0" encoding="utf-8"?>
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
  <PropertyChanged />
</Weavers>

Fody Properties

Now, Simply add one property with { get; set; }.

public class LoginPageViewModel: INotifyPropertyChanged
{
    public LoginPageViewModel()
    {
    }
    //Fody property
    public string Password { get; set; }
}

XAML Binding

Now, bind your property in the XAML element.

<Entry Placeholder="Password" IsPassword="True" Text="{Binding Password}"/>

Result

Now see fody is reducing more number of lines code. We don't need to create the field like a normal one. That is why fody is good for MVVM.

Conclusion

I hope you have understood how to use fody in MVVM in Xamarin.Forms App

Thanks for reading. Please share your comments and feedback. Happy Coding :)


Similar Articles