KeiStory

.NET MAUI SearchBar

 

SearchBar 컨트롤을 사용하는 방법을 알아봅니다.

1. No MVVM

- 문자열이 입력되는 순간 검색이 이루어집니다.

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="Maui.SearchBarTest.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

    <ScrollView>
        <Grid Margin="10" RowDefinitions="40,*">
            <!--  NO MVVM  -->
            <SearchBar
                x:Name="searchBar"
                Grid.Row="0"
                Placeholder="Search items..."
                TextChanged="SearchBar_TextChanged" />
            <CollectionView x:Name="collectionView" Grid.Row="2">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <StackLayout Orientation="Horizontal">
                            <Label Margin="10" Text="{Binding ID}" />
                            <Label Margin="10" Text="{Binding Name}" />
                        </StackLayout>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </Grid>
    </ScrollView>
</ContentPage>

MainPage.xaml.cs

using Maui.SearchBarTest.Services;

namespace Maui.SearchBarTest
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            // NO MVVM
            this.collectionView.ItemsSource = DataService.GetResult();
        }

        private void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (string.IsNullOrEmpty(e.NewTextValue))
            {
                this.collectionView.ItemsSource = DataService.GetResult();
            }
            else
            {
                this.collectionView.ItemsSource = DataService.GetSearchResults(e.NewTextValue);
            }
        }
    }
}

ItemModel.cs

namespace Maui.SearchBarTest.Models
{
    public class ItemModel
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

DataService.cs

using Maui.SearchBarTest.Models;

namespace Maui.SearchBarTest.Services
{
    public class DataService
    {
        private static List<ItemModel> results;

        public static List<ItemModel> GetResult()
        {
            results = new List<ItemModel>();

            results.Add(new ItemModel() { ID = 1, Name = "A홍길동" });
            results.Add(new ItemModel() { ID = 2, Name = "B강감찬" });
            results.Add(new ItemModel() { ID = 3, Name = "C이순신" });
            results.Add(new ItemModel() { ID = 4, Name = "C이율곡" });
            results.Add(new ItemModel() { ID = 4, Name = "B강이식" });
            results.Add(new ItemModel() { ID = 4, Name = "D홍두께" });
            results.Add(new ItemModel() { ID = 4, Name = "C이이" });
            results.Add(new ItemModel() { ID = 4, Name = "E유관순" });

            return results;
        }

        public static List<ItemModel> GetSearchResults(string query)
        {
            return results.Where(c => c.Name.Contains(query) == true).ToList();
        }
    }
}



2. MVVM

- 검색 버튼을 누르커나 키보드의 검색키 누르면 검색이 이루어집니다.

- 문제점 : 아래와 같이 처리한 경우 데이터 초기 목록 조회가 안됩니다

공백인 경우 SearchCommand 명령이 수행되지 않기 때문입니다.

이는 searchBar 의 Text 를 Property 로 선언 후 처리하면 가능합니다.

 

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="Maui.SearchBarTest.MainPage"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">

    <ScrollView>
        <Grid Margin="10" RowDefinitions="40,*">
            <!--  MVVM  -->
            <SearchBar
                x:Name="searchBar"
                Grid.Row="0"
                Placeholder="Search items..."
                SearchCommand="{Binding SearchCommand}"
                SearchCommandParameter="{Binding Text, Source={x:Reference searchBar}}" />
            <CollectionView
                x:Name="collectionView"
                Grid.Row="2"
                ItemsSource="{Binding SearchResults}">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <StackLayout Orientation="Horizontal">
                            <Label Margin="10,0,0,0" Text="{Binding ID}" />
                            <Label Margin="10,0,0,0" Text="{Binding Name}" />
                        </StackLayout>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </Grid>
    </ScrollView>
</ContentPage>

MainPage.xaml.cs

using Maui.SearchBarTest.Services;
using Maui.SearchBarTest.ViewModels;

namespace Maui.SearchBarTest
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            // MVVM
            this.BindingContext = new MainViewModel();
        }
    }
}

MainViewModel.cs

using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Input;
using Maui.SearchBarTest.Models;
using Maui.SearchBarTest.Services;

namespace Maui.SearchBarTest.ViewModels
{
    public class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        private List<ItemModel> searchResults;
        public List<ItemModel> SearchResults
        {
            get
            {
                return searchResults;
            }
            set
            {
                searchResults = value;
                NotifyPropertyChanged();
            }
        }

        public ICommand SearchCommand => new Command<string>((query) =>
        {
            if (string.IsNullOrEmpty(query))
            {
                SearchResults = DataService.GetResult();
            }
            else
            {
                SearchResults = DataService.GetSearchResults(query);
            }
        });

        public MainViewModel()
        {
            SearchResults = DataService.GetResult();
        }
    }
}

 

검색 전 / 검색 후

 

 

소스
https://github.com/kei-soft/KJunBlog/tree/master/Maui.SearchBarTest

 

KJunBlog/Maui.SearchBarTest at master · kei-soft/KJunBlog

Contribute to kei-soft/KJunBlog development by creating an account on GitHub.

github.com

반응형

공유하기

facebook twitter kakaoTalk kakaostory naver band