Xamarin Shell: Fitur Search Pada Shell

1. Untuk membuat halaman yang memiliki fitur search, tambahkan halaman baru dengan nama ContohSearch.

2. Kemudian pada project buat folder dengan nama Data dan Controls.

3. Folder Data digunakan untuk menambahkan list untuk data dummy. Pada folder Data tambahkan file dengan nama MonkeyData.cs

public static IList<Animal> Monkeys { get; private set; }

        static MonkeyData()
        {
            Monkeys = new List<Animal>();

            Monkeys.Add(new Animal
            {
                Name = "Baboon",
                Location = "Africa & Asia",
                Details = "Baboons are African and Arabian Old World monkeys belonging to the genus Papio, part of the subfamily Cercopithecinae.",
                ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Papio_anubis_%28Serengeti%2C_2009%29.jpg/200px-Papio_anubis_%28Serengeti%2C_2009%29.jpg"
            });

            Monkeys.Add(new Animal
            {
                Name = "Capuchin Monkey",
                Location = "Central & South America",
                Details = "The capuchin monkeys are New World monkeys of the subfamily Cebinae. Prior to 2011, the subfamily contained only a single genus, Cebus.",
                ImageUrl = " https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Capuchin_Costa_Rica.jpg/200px-Capuchin_Costa_Rica.jpg"
            });
}}

4. Kemudian tambahkan juga folder Controls, kemudian tambahkan file dengan nama MonkeySearchHandler.cs. file ini digunakan untuk menangani mekanisme search.

    public class MonkeySearchHandler : SearchHandler
    {
        protected override void OnQueryChanged(string oldValue, string newValue)
        {
            base.OnQueryChanged(oldValue, newValue);

            if (string.IsNullOrWhiteSpace(newValue))
            {
                ItemsSource = null;
            }
            else
            {
                ItemsSource = MonkeyData.Monkeys
                    .Where(monkey => monkey.Name.ToLower().Contains(newValue.ToLower()))
                    .ToList<Animal>();
            }
        }

        protected override async void OnItemSelected(object item)
        {
            base.OnItemSelected(item);
            await Task.Delay(1000);
           await Shell.Current.GoToAsync($"monkeydetails?name={((Animal)item).Name}");        }
    }

5. Pada ContohSearch tambahkan kode xaml berikut ini:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage mc:Ignorable="d"
             x:Class="Latihan1.Bab4.ContohSearch"
             xmlns:controls="clr-namespace:Latihan1.Controls"
             xmlns:data="clr-namespace:Latihan1.Data"
             Title="Monkey">
    <Shell.SearchHandler>
        <controls:MonkeySearchHandler Placeholder="Enter search term"
                                      ShowsResults="true"
                                      DisplayMemberName="Name" />
    </Shell.SearchHandler>
    <CollectionView Margin="20"
                    ItemsSource="{x:Static data:MonkeyData.Monkeys}"
                    ItemTemplate="{StaticResource AnimalTemplate}"
                    SelectionMode="Single"
                    SelectionChanged="OnCollectionViewSelectionChanged" />
</ContentPage>

6. Kemudian tambahkan kode pada method OnCollectionViewSelectionChanged.

        async void OnCollectionViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                string monkeyName = (e.CurrentSelection.FirstOrDefault() as Animal).Name;
                await Shell.Current.GoToAsync($"monkeydetails?name={monkeyName}");
            }
            catch (Exception ex)
            {

                await DisplayAlert("Error", $"{ex.InnerException.Message}","OK");
            }
            
        }

7. Karena ketika kita memilih salah satu item akan dibuka halaman details, maka tambahkan halaman baru dengan nama DetailSearch.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage 
             x:Class="Latihan1.Bab4.DetailSearch" Title="Monkey Detail">
    <ScrollView>
        <StackLayout Margin="20">
            <Label Text="{Binding Name}" 
                   HorizontalOptions="Center" />
            <Label Text="{Binding Location}" 
                   FontAttributes="Italic" 
                   HorizontalOptions="Center" />
            <Image Source="{Binding ImageUrl}" 
                   HeightRequest="200" 
                   WidthRequest="200" 
                   HorizontalOptions="CenterAndExpand" />
            <Label Text="{Binding Details}"/>
        </StackLayout>
    </ScrollView>
</ContentPage>

8. Kemudian pada folder ViewModels tambahkan class dengan nama MonkeyDetailViewModel, kemudian tambahkan kode berikut ini:

    [QueryProperty("MonkeyName", "name")]
    public class MonkeyDetailViewModel : INotifyPropertyChanged
    {
        public string MonkeyName
        {
            set
            {
                Animal monkey = MonkeyData.Monkeys.FirstOrDefault(m => m.Name == Uri.UnescapeDataString(value));

                if (monkey != null)
                {
                    Name = monkey.Name;
                    Location = monkey.Location;
                    Details = monkey.Details;
                    ImageUrl = monkey.ImageUrl;
                    OnPropertyChanged("Name");
                    OnPropertyChanged("Location");
                    OnPropertyChanged("Details");
                    OnPropertyChanged("ImageUrl");
                }
            }
        }

        public string Name { get; set; }
        public string Location { get; private set; }
        public string Details { get; private set; }
        public string ImageUrl { get; private set; }

        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion
    }

9. Tambahkan route untuk ke halaman detail pada AppShell.cs

   Routing.RegisterRoute("monkeylist", typeof(ContohSearch));
   Routing.RegisterRoute("monkeydetails", typeof(DetailSearch));

10. Kemudian jalankan aplikasinya, dan pilih menu navigasi Monkey List.

image

11. Ketikan keyword yang diinginkan, setelah dipilih maka akan ditampilkan halaman detail.

image

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 )

Google photo

You are commenting using your Google 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