Telerik blogs
.NET MAUI News Hub Developing

Instantly reflecting data changes in our user interface is possible through binding. Let’s see how to bind data in .NET MAUI.

Howdy! 🙋‍♀ It’s a pleasure for me to have you here! 💚

One of the most important features of an application is that it has the ability to dynamically link data to each of our views. This is where data binding comes in—it is the technique of binding properties so that changes to a property are automatically reflected in our UI. Thus we can avoid handling hard-coded data and instead make a more flexible environment for users.

In this post, we will see how to apply data binding and the different types available in .NET MAUI.

What Is Data Binding?

Data binding allows us to separate our UI from the business logic, but maintain the communication between both, making a bridge that allows us to bring the data to our UI.

For this, you only have to use the word “Binding” between braces followed by the value that you want to reflect in the properties of the control you prefer. It’s a feature that we can take advantage of mainly if we are using the Model-View-ViewModel (MVVM) architecture model.

According to our explanation above, a basic example of a binding would be like the following:

<Label Text="{Binding FirstName}" />

Advantages of Using Data Bindings

  • By using data bindings, you have the opportunity to change the values that you will present in your View without the need to update the code because it will be completed automatically if you change your data source. (For example, your source can be an API implemented in the business logic.)
  • Using data bindings maintains an immediate communication with the information that is shown to the user in the UI.
  • You maintain better organization in your project, since you can separate your views from the business logic together with MVVM.

How To Use Data Bindings

For the purposes of a better understanding of this topic, we are going to divide an example scenario into steps where we could use a binding.

Step 1: Declare a Simple Model

We will declare the Student class, which will contain the following attributes:

  • FirstName
  • LastName
  • Phone

⚠ We create this model to declare the data structure that we will be presenting in our example UI.

public class Students
{
     private string _firstName = string.Empty;
     private string _lastName = string.Empty;
     private string _phone = string.Empty;
 
    public string FirstName
    {
        get { return _firstName; }
        set { _firstName = value; }
    }

    public string LastName
    {
	    get { return _lastName; }
	    set { _lastName = value; }
    }

    public string Phone
    { 
	    get { return _phone; }
	    set { _phone = value; }
    }
     
    public Students(string firstName, string lastName, string phone)
    {
	    FirstName = firstName;
	    LastName = lastName;
	    Phone = phone;
    }
}

Step 2: Creating a ViewModel

Now we will create a ViewModel, which we will fill with mock data the structure of our model.

⚠ An important point to note here is that in this example we are using mock data—however, you can use any data source you need, for example consume an API.

public class StudentsViewModel
{

    private List<Students> studentsCollection = new List<Students>();

    public StudentsViewModel()
    {
	    studentsCollection.Add(new Students("Marie", "White", "+1-809-554-6055"));
	    studentsCollection.Add(new Students("Paola", "Pullman", "+1-809-506-5655"));
	    studentsCollection.Add(new Students("Joseph", "McDonalds", "+1-809-684-4876"));
    }
    
    public List<Students> StudentsCollection
    {
	    get { return studentsCollection; }
	    set { studentsCollection = value; }
    }
}

Step 3: Working With the View

Finally, let’s bring that information into view with a binding!

Basically the keyword to use is “Binding”—it’s responsible for indicating to the property of the control to which we want to assign, that the value of this property will come from the business logic.

How to do it? Let’s understand its structure.

.NET MAUI binding structure: 1. Select your control, 2. Select your Property, 3. Select the property name to be Binded.

In addition to the steps shown in the image, to assign a Binding you must follow these steps:

  • Look for the property whose value you want to bring to your UI to be binded. For example, in Step 1 of our previous scenario we have a model with three attributes. We are going to choose FirstName for this example.
  • Once the steps above are complete, add them to the property, as in the following example:
<Label Text="{Binding  FirstName}" />

Let’s see the example in a CollectionView to show our data in a list!

We will use a CollectionView to be able to present a binded/bound list! As you can see, we only have to call the name of the Collection declared in our ViewModel, and then add the attributes (FirstName, etc.).

<StackLayout Margin="50">
    <CollectionView ItemsSource="{Binding StudentsCollection}">
	    <CollectionView.ItemTemplate>
		    <DataTemplate>
			    <StackLayout BackgroundColor="Pink" Orientation="Horizontal" HeightRequest="50">
				    <Label Text="{Binding FirstName}"/>
				    <Label Text="{Binding LastName}"/>
				    <Label Text="{Binding Phone}"/>
			    </StackLayout>
		    </DataTemplate>
	    </CollectionView.ItemTemplate>
    </CollectionView>
</StackLayout>

For this example, we only need one point—add a BindingContext to our page. We will do it as follows:

In your Student.xaml.cs, add your ViewModel (in this case, StudentsViewModel) to the BindingContext, as shown below:

BindingContext = new StudentsViewModel();

And finally, you can have a result like the follow:

Bound CollectionView Sample

Binding Modes

Bindings have binding modes that define how the data communication will be established. In this case, the OneWay Mode is established by default for most of the bindable properties. There are also other modes to establish if necessary. Let’s see the main ones:

TwoWay Bindings

TwoWay is when data bindings are used with Model-View-ViewModel (MVVM). The ViewModel class is the data binding source and the view—these have bidirectional responses for data updates. This is because the user probably wants some view on the page to be initialized with the value of the corresponding property in the ViewModel, and changes to the view should also be updated.

We have some properties that already have a default binding mode of TwoWay, for instance:

PropertyControl
DateDatePicker
TextEditor, Entry, SearchBar, and EntryCell
SelectedIndex and SelectedItemPicker
TimeTimePicker

Now, how would we add that mode to our property? It’s easy! Look at the following example:

{Binding FirstName Mode="TwoWay"}

One-Way-to-Source Bindings

It’s a read-only mode, it’s assigned by default in most properties (therefore you don’t have to indicate it in your code), and it’s responsible for reporting the information only unilaterally.

{Binding FirstName}

Commands

I imagine you’re wondering something like, “And is there something like that I can replace events with?” The answer is yes!

As with data, we can also bind methods that should be executed in reaction to a specific activity in the view, such as clicking a button. We can do it with Commands. Let’s see an example scenario of how to implement it!

Step 1: Declare the Command in Your ViewModel

We have the ICommand interface, which helps us to use the Command in the following way:

public ICommand MyCommand { private set; get; }

Step 2: Call the Command in Your XAML

To add a Command, you just have to follow the next steps:

  • Add the Command to your control.
  • Then add the name of the command you want to add. For example:
         “{Binding YourCommand}”
    (As you’ll note, the word “Binding” is always kept.)

Finally, your Command should be as follows:

<Button Text="Click here please"
Command="{Binding MyCommand}"

Step 3: Give a Body to Your Command in the ViewModel

MyCommand = new Command(
    execute: () =>
    {
    Entry = Entry.Substring(0, Entry.Length - 1);
	    if (Entry == "")
	    {
	    Entry = "0";
	    }
	    RefreshCanExecutes();
	    },
    canExecute: () =>
    {
    	return Entry.Length > 1 || Entry != "0";
    });

Here I added an example from the official documentation.

And your Command is done! 💪

Wrapping Up

You are now ready to work with basic bindings in .NET MAUI!

Thank you for reading this article, I hope it’s a super useful topic for you!💚💕

See you next time! 💁‍♀️

References


LeomarisReyes
About the Author

Leomaris Reyes

Leomaris Reyes is a Software Engineer from the Dominican Republic, with more than 5 years of experience. A Xamarin Certified Mobile Developer, she is also the founder of  Stemelle, an entity that works with software developers, training and mentoring with a main goal of including women in Tech. Leomaris really loves learning new things! 💚💕 You can follow her: Twitter, LinkedIn , AskXammy and Medium.

Related Posts

Comments

Comments are disabled in preview mode.