Click here to Skip to main content
15,889,403 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
hi, now i am trying to bind class property to listview, code is running fine but nothin showing on screen. any help will be deeply appreciated thanks.


What I have tried:

C#
using System.Collections.ObjectModel;
using System.Reflection.Metadata.Ecma335;
using System.Security.Cryptography.X509Certificates;

namespace MauiApp12;
public partial class MainPage : ContentPage
{
    public class contacts
    {
        //https://stackoverflow.com/questions/11317587/return-a-string-from-a-method-in-c-sharp
        public string FirstName { get; set; }
    }
    public contacts x = new contacts() { FirstName="what is your name"};
    //public ObservableCollection<contacts> contact { get; set; } = new ObservableCollection<contacts>("my name is mehdi") { new contacts("what is your name") {FirstName="my first name is mehdi"; } }; 
    public MainPage()
    {
        InitializeComponent();
    }
    private async void OnCounterClicked(object sender, EventArgs e)
    {

        //await DisplayAlert("alert",x.fullNameMethod(), "ok");
        //lv.ItemsSource = x;
        lv.SetBinding(ItemsView.ItemsSourceProperty, "FirstName");
    }
    }

XAML
?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MauiApp12.MainPage">

    <ScrollView>
        <VerticalStackLayout
            Spacing="25"
            Padding="30,0"
            VerticalOptions="Center">

            <ListView x:Name="lv" ItemsSource="{Binding contact}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid Padding="10">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="Auto" />
                                    <RowDefinition Height="Auto" />
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto" />
                                    <ColumnDefinition Width="Auto" />
                                </Grid.ColumnDefinitions>
                                                                <Label Grid.Column="1"
                           Text="{Binding FirstName}"
                           FontAttributes="Bold" />
                                                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <Image
                Source="dotnet_bot.png"
                SemanticProperties.Description="Cute dot net bot waving hi to you!"
                HeightRequest="200"
                HorizontalOptions="Center" />

            <Label
                Text="Hello, World!"
                SemanticProperties.HeadingLevel="Level1"
                FontSize="32"
                HorizontalOptions="Center" />

            <Label
                Text="Welcome to .NET Multi-platform App UI"
                SemanticProperties.HeadingLevel="Level2"
                SemanticProperties.Description="Welcome to dot net Multi platform App U I"
                FontSize="18"
                HorizontalOptions="Center" />

            <Button
                x:Name="CounterBtn"
                Text="Click me"
                SemanticProperties.Hint="Counts the number of times you click"
                Clicked="OnCounterClicked"
                HorizontalOptions="Center" />

        </VerticalStackLayout>
    </ScrollView>

</ContentPage>
Posted
Updated 5-Jun-23 0:47am
v3
Comments
Graeme_Grant 4-Jun-23 7:10am    
Where's the view that is meant to bind to the collection? Please update your question with the missing xaml. Chances are is that you have not correctly set your DataContext.
suhail malik 2023 4-Jun-23 7:33am    
<listview x:name="lv" itemssource="{Binding variables}">
IN FIRST ATTEMPT I TRIED WITH XAML WITH SAME RESULT. NOW I AM TRYING TO CREATE LIST VIEW ON RUNTIME IN CODEBEHIND BOTH ATTEMPTS ARE GIVING ME THE SAME RESULT NO DATA ON SCREEN
Graeme_Grant 4-Jun-23 7:47am    
Do not use ALL CAPS ... it is called SCREAMING.

Please update the question with the XAML as requested as we can not see your screen from here.
suhail malik 2023 4-Jun-23 7:47am    
I HAVE FIGURED IT OUT WITH XAML, NOW HOW CAN I ADD LIST ON RUNTIME AND BIND DATA TO TO LIST VIEW
Richard MacCutchan 4-Jun-23 8:03am    
Stop shouting! Writing in all capitals is considered shouting on the internet, and makes it appear that you are demanding special service.

1 solution

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:
C#
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:
C#
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:
XML
<?xml version="1.0" encoding="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:
C#
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[^]
 
Share this answer
 
v4
Comments
suhail malik 2023 5-Jun-23 6:57am    
Error CS0103 The name 'DataContext' does not exist in the current context
what to do
Graeme_Grant 5-Jun-23 7:22am    
I have updated my answer. The DataContext property should be BindingContext, my bad. I have posted a working example and links for further information.
suhail malik 2023 5-Jun-23 12:28pm    
yes for this kind of simple collection i set the listview.itemssource to list of collections then it worket. now i am going bit further and trying to bind collection of class items with properties to list view i will post another question. i deeply appreciate your effort for helping me out

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900