noor
noor

Reputation: 11

xamarin BindingContext with ViewModel

I'm having issue with data binding I have a tabbed page contains two tabs chats and groups.

<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            x:Class="bashal.MainPage" Title="Bashal"
            xmlns:local="clr-namespace:bashal.Views"
            xmlns:xct="http://xamarin.com/schemas/2020/toolkit"
                
            xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core"
                
            android:TabbedPage.ToolbarPlacement="Bottom" >
    
    <local:chatPage Title="chats" />
    <local:groupsPage Title="Groups" NavigationPage.HasBackButton="False" />
</TabbedPage>

And the first tab called chat contains this page.

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  x:Class="bashal.Views.chatPage"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:ViewModels="clr-namespace:bashal.ViewModels" 
        Title="home" >
        
    <ContentPage.BindingContext>
        <ViewModels:chatPageViewModel/>
    </ContentPage.BindingContext>
        
    <StackLayout>
        <CollectionView>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Label Text="{Binding name}"/>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>    
    </StackLayout>
</ContentPage>

And I'm trying to do data binding with this ViewModel class from folder called vaiewModels

namespace bashal.ViewModels
{
    class chatPageViewModel
    {
        ObservableCollection<rooms> rooms;
        public chatPageViewModel()
        {
            rooms = new ObservableCollection<rooms>
            {
                new rooms {name = "user1", discrbtion= "welcome"},
                new rooms {name = "user2", discrbtion= "welcome"},
                new rooms {name = "user3", discrbtion= "welcome"},
                new rooms {name = "user4", discrbtion= "welcome"},
                new rooms {name = "user5", discrbtion= "welcome"},
                new rooms {name = "user6", discrbtion= "welcome"}
            };
        }
    }
}

And this the room class

public  class rooms
{
    public string name { get; set; }
    public string discrbtion { get; set; }
}

But the data doesn't show what I'm doing wrong?

Upvotes: 0

Views: 338

Answers (1)

Jason
Jason

Reputation: 89082

first, you need to assign an ItemsSource

<CollectionView ItemSource="{Binding rooms}" >

you can only bind to public properties, so rooms needs to be a public property

public ObservableCollection<rooms> rooms { get; set; }

Upvotes: 1

Related Questions