728x90
반응형
728x170

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 명령이 수행안됨)

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();
        }
    }
}

 

3. 이슈

가장 큰 문제는 아래처럼 한글 입력이 이상하게되어 한글 검색은 불가능하다 ㅜㅠ
('가' 를 입력한 모습)

 

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

728x90
반응형
그리드형
Posted by kjun

댓글을 달아 주세요