Introduction
In this article, we will explore how to bind an ImageSource in a .NET MAUI app using the Model-View-ViewModel (MVVM) pattern and SQLite. We will create a simple app that displays a list of users and allows the user to edit a selected item.
Prerequisites
To follow along with this guide, you should have a basic understanding of C# and .NET MAUI. You should also have the following tools installed:
-
.NET 6.0 SDK -
Visual Studio 2022with the .NET MAUI workload installed
Creating the App
Let's start by creating a new .NET MAUI app in Visual Studio. We'll call it ImageSourceBinding.
Setting up the ViewModel
Next, we'll create a ViewModel for our app. This ViewModel will contain an ObservableCollection of User objects, which we will use to bind to our view.
public class MainViewModel
{
public ObservableCollection Users { get; set; }
public MainViewModel()
{
Users = new ObservableCollection();
}
public async Task LoadUsersAsync()
{
// Load users from SQLite database
}
}
Setting up the View
Now let's create the view for our app. We'll use an Image control to display the user's profile picture, and a ListView to display the list of users.
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ImageSourceBinding.MainPage">
<ContentPage.BindingContext>
<local:MainViewModel />
</ContentPage.BindingContext>
<StackLayout>
<Image Source="{Binding SelectedUser.ProfilePicture}" />
<ListView ItemsSource="{Binding Users}" SelectedItem="{Binding SelectedUser}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Image Source="{Binding ProfilePicture}" WidthRequest="50" HeightRequest="50" />
<Label Text="{Binding Name}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage>
Setting up the User Model
Finally, let's create a User model that contains a ProfilePicture property of type ImageSource.
public class User
{
public string Name { get; set; }
public ImageSource ProfilePicture { get; set; }
}
Loading Data from SQLite
Now that we have our app set up, let's load some data from a SQLite database. We'll use the SQLitePCL library to interact with the database.
public async Task LoadUsersAsync()
{
var db = new SQLiteConnection(Path.Combine(FileSystem.AppDataDirectory, "users.db"));
var users = await db.QueryAsync<User>("SELECT * FROM User");
foreach (var user in users)
{
user.ProfilePicture = ImageSource.FromFile(Path.Combine(FileSystem.AppDataDirectory, user.ProfilePicturePath));
Users.Add(user);
}
}
In this article, we have explored how to bind an ImageSource in a .NET MAUI app using the MVVM pattern and SQLite. We have created a simple app that displays a list of users and allows the user to edit a selected item. By using an ObservableCollection and binding to the SelectedItem property of a ListView, we can easily update the UI when the user selects a different item.