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.
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}" />
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.
We will declare the Student class, which will contain the following attributes:
⚠ 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;
}
}
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; }
}
}
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.
In addition to the steps shown in the image, to assign a Binding you must follow these steps:
<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:
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 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:
Property | Control |
---|---|
Date | DatePicker |
Text | Editor, Entry, SearchBar, and EntryCell |
SelectedIndex and SelectedItem | Picker |
Time | TimePicker |
Now, how would we add that mode to our property? It’s easy! Look at the following example:
{Binding FirstName Mode="TwoWay"}
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}
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!
We have the ICommand interface, which helps us to use the Command in the following way:
public ICommand MyCommand { private set; get; }
To add a Command, you just have to follow the next steps:
Finally, your Command should be as follows:
<Button Text="Click here please"
Command="{Binding MyCommand}"
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! 💪
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! 💁♀️
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.