The code-behind looks different to the other version of this question.
In the XAML, you bind the
variables
property to the
ListView
control however the
DataContext
is not set.
Do the following in the Code-Behind:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
DataContext = this;
}
}
Now the Binding data context is set, the ListView
binding will work. (note: this works for WPF/UWP apps - see below for MAUI)
Also, All public properties should me camel case:
public ObservableCollection<MyVariables> Variables { get; set; }
= new ObservableCollection<MyVariables>()
{
new MyVariables("hello sir how are you")
};
UPDATE
For Maui, We need to use
BindingContext
. Here is a working example for you.
1. Start a new project.
2. MainPage.xaml:
="1.0"="utf-8"
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MauiApp1.MainPage">
<ListView ItemsSource="{Binding Items}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Label Text="{Binding .}"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage>
3. Code-Behind - MainPage.xaml.cs:
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
BindingContext = this;
}
public ObservableCollection<string> Items { get; set; } = new ObservableCollection<string>
{
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5",
};
}
Now run and you will see your list.
For more on Data Binding:
.Net MAUI Data binding - Microsoft Learn[
^]
For more on the ListView:
.Net MAUI Controls - ListView - Microsoft Learn[
^]