简体   繁体   中英

Xamarin Forms - how to display/Bind List in ListView?

I'm creating a cart where i store all of my orders , How to display List in ListView?

i tried doing these codes

CustomerOrder.cs

public class CustomerOrder
    {
        public string menuname { get; set; }
        public string price { get; set; }
        public string qty { get; set; }
        public string mcode { get; set; }
    }

    public class CustList
    {
        //i want to display/bind this in Listview
        public List<CustomerOrder> CUSTOMER_ORDER { get; set; }
    }

OrderCart.xaml

<ListView x:Name="MyCart" ItemSelected="MyCart_ItemSelected"  ItemsSource="{Binding CUSTOMER_ORDER}" RowHeight="50">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell >
                    <Grid>

                                <StackLayout Orientation="Horizontal">
                                    <Label  Text="{Binding menuname}" Font="30" TextColor="Black" FontAttributes="Bold"/>
                                    <Label  Text="{Binding qty}" Font="30" TextColor="Black" FontAttributes="Bold"/>
                                    <Label  Text="{Binding price}" Font="30" TextColor="Black" FontAttributes="Bold"/>
                                    <Label  Text="{Binding mcode}" Font="30" TextColor="Black" FontAttributes="Bold"/>
                                </StackLayout>
                  </Grid>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>

    </ListView>

You might missing PropertyChanged event.

public class CustList:INotifyPropertyChanged
    {
        //i want to display/bind this in Listview
        private List<CustomerOrder> _CUSTOMER_ORDER
        public List<CustomerOrder> CUSTOMER_ORDER 
        { 
          get{return _CUSTOMER_ORDER;}
          set{
              _CUSTOMER_ORDER=value;
              OnPropertyChanged("CUSTOMER_ORDER");
             } 
        }

        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, 
            new PropertyChangedEventArgs(propertyName));
        }
    }

And one more thing is you have to apply bindingcontext for your xaml if you are missing that.

If MyCart is any instance of CustList,

In your bindings, you can {Binding CUSTOMER_ORDER.menuname}.

You have to give it path to the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM