how to use BindableLayout in maui?

mc 3,726 Reputation points
2023-04-16T00:29:15.2333333+00:00

I want to use BindableLayout but



<Grid BindableLayout.ItemsSource="{Binding Customers}"> 

it tell me there is no Customers in ViewModel but I set it.

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
2,976 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 36,951 Reputation points Microsoft Vendor
    2023-04-17T02:40:32.09+00:00

    Hello,

    For how to use BindableLayout in maui, you could refer to the following steps:

    Step 1: Create the ViewModel:

    public class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        private ObservableCollection<Customer> _customers;
        public ObservableCollection<Customer> Customers
        {
            get { return _customers; }
            set
            {
                if (value != null)
                {
                    _customers = value;
                }
            }
       }
        public MainViewModel()
        {
            Customers = new ObservableCollection<Customer>();
            Customers.Add(new Customer { Name = "test1" });
        }
    }
    

    Step 2: Use your ViewModel in XAML:

    <ContentPage 
                 ...
                 xmlns:local="clr-namespace:MauiApp3">
    	<ContentPage.BindingContext>
            	<local:MainViewModel/>
    	</ContentPage.BindingContext>
    

    it tell me there is no Customers in ViewModel but I set it.

    If you declare a ViewModel in code-behind, such as BindingContext = new MainViewModel();, you will be prompted in the XAML file that the properties in the ViewModel cannot be found, because the declaration in the code-behind takes effect at runtime. Please refer to Compiled bindings to get more details.

    Step 3: Use BindableLayout in Grid:

    <Grid BindableLayout.ItemsSource="{Binding Customers}">
                <BindableLayout.ItemTemplate>
                    <DataTemplate>
                        <Label Text="{Binding Name}"/>
                    </DataTemplate>
                </BindableLayout.ItemTemplate>
    </Grid>
    

    If you want to know more about BindableLayout, please refer to BindableLayout.

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments