Xamarin Forms: Menambahkan Tombol pada ListView

Pada artikel kali ini saya akan mencontohkan bagaimana cara menambahkan tombol kedalam kontrol ListView. Untuk mem-binding event yang ada pada tombol kita akan menggunakan model arsitektur MVVM (Model View View Model).

Untuk kasus yang lebih komplek, kita juga dapat menambahkan kontrol seperti tombol pada ListView. Kita juga dapat menambahkan event handler yang dapat dipanggil ketika tombol yang dibuat didalam kontrol ListView tersebut diklik.

1. Tambahkan xaml page baru dengan nama ListViewButton.xaml.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Bab3.ListViewButton">
  <ContentPage.Padding>
    <OnPlatform x:TypeArguments="Thickness">
      <OnPlatform.iOS>10,20,10,5</OnPlatform.iOS>
      <OnPlatform.Android>10,5,10,5</OnPlatform.Android>
    </OnPlatform>
  </ContentPage.Padding>
  <StackLayout Orientation="Vertical">
    <ListView ItemsSource="{Binding ListItems}" RowHeight="100" BackgroundColor="Black" HasUnevenRows="True">
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <StackLayout HorizontalOptions="StartAndExpand" Orientation="Horizontal" Padding="5,10,5,15">
              <StackLayout HorizontalOptions="Start" Orientation="Vertical">
                <Label HorizontalOptions="Start" FontSize="20" FontAttributes="Bold" TextColor="White" Text="{Binding Title}"/>
                <Label HorizontalOptions="Start" FontSize="12" FontAttributes="Bold" TextColor="White" Text="{Binding Description}"/>
              </StackLayout>
              <StackLayout HorizontalOptions="EndAndExpand" Orientation="Horizontal" WidthRequest="260">
                <Label HorizontalOptions="Center" FontSize="25" TextColor="Aqua" Text="{Binding Price}" />
                <Button Text="Buy Now" BackgroundColor="Teal" HorizontalOptions="End" Command="{Binding BuyCommand}"/>
                <Button Text="Sell" BackgroundColor="Purple" TextColor="White" HorizontalOptions="End" Command="{Binding SellCommand}"/>
              </StackLayout>
            </StackLayout>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
  </StackLayout>
</ContentPage>

2. Tambahkan juga kode pada file ListViewButton.xaml.cs. Tambahkan juga class ListItem yang berisi informasi properti yang akan ditampilkan pada list beserta dengan command-nya.

using Xamarin.Forms;

namespace Bab3
{
    public class ListItem : BindableObject
    {
        public string Source { get; set; }
        private string title;

        public string Title
        {
            get { return title; }
            set { title = value;
                OnPropertyChanged("Title");
            }
        }

        public string Description { get; set; }
        public string Price { get; set; }

        private Command buyCommand;

        public Command BuyCommand
        {
            get { return buyCommand; }
            set { buyCommand = value;
                OnPropertyChanged("BuyCommand");
            }
        }

        private Command sellCommand;

        public Command SellCommand
        {
            get { return sellCommand; }
            set { sellCommand = value;
                OnPropertyChanged("SellCommand");
            }
        }


        public ListItem()
        {
            BuyCommand = new Command(BuyRequested);
            SellCommand = new Command(SellRequested);
        }

        void SellRequested()
        {
            MessagingCenter.Send<ListItem>(this, "SellRequested");
        }

        void BuyRequested()
        {
            MessagingCenter.Send<ListItem>(this, "BuyRequested");
        }

    }

    public class ListViewButtonViewModel : BindableObject
    {
        readonly Func<string, string, string, Task> displayAlertAction;

        private List<ListItem> listItems;

        public List<ListItem> ListItems
        {
            get { return listItems; }
            set
            {
                listItems = value;
                OnPropertyChanged("ListItems");
            }
        }



        public ListViewButtonViewModel(Func<string,string,string,Task> displayAlertAction)
        {
            this.displayAlertAction = displayAlertAction;
            ListItems = new List<ListItem> {
                new ListItem {Title = "First", Description="1st item", Price="Rp.100.00"},
                new ListItem {Title = "Second", Description="2nd item", Price="Rp.200.00"},
                new ListItem {Title = "Third", Description="3rd item", Price="Rp.300.00"}
            };

            MessagingCenter.Subscribe<ListItem>(this, "BuyRequested",BuyRequested);
            MessagingCenter.Subscribe<ListItem>(this, "SellRequested", (sender) =>
            {
                var data = (ListItem)sender;
                data.Title = "Item Sold";
            });
            
        }

        

        void BuyRequested(ListItem listItem)
        {
            displayAlertAction.Invoke("Button", listItem.Title + " was clicked", "OK");
        }
    }

    public partial class ListViewButton : ContentPage
    {
        public ListViewButton()
        {
            InitializeComponent();

            BindingContext = new ListViewButtonViewModel(DisplayAlert);

            
        }
    }
}

3. Hasil dari program yang dijalankan pada emulator adalah sebagai berikut:

image

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s