KeiStory

.NET MAUI Picker 사용 방법

 

Picker는 사용자가 제공된 옵션 중에서 하나를 선택할 수 있게 해주는 컨트롤입니다

기본 사용법을 알아봅니다.

 

XAML

<Picker
    Title="Select Country"
    BackgroundColor="Green"
    TextColor="White">
    <Picker.ItemsSource>
        <x:Array Type="{x:Type x:String}">
            <x:String>Korea</x:String>
            <x:String>Sudan</x:String>
            <x:String>United States</x:String>
            <x:String>Japan</x:String>
            <x:String>China</x:String>
            <x:String>Macedonia</x:String>
            <x:String>Greece</x:String>
        </x:Array>
    </Picker.ItemsSource>
</Picker>

XAML 실행결과

 

MVVM

<HorizontalStackLayout>
    <Picker
        x:Name="picker"
        Title="Select Country"
        BackgroundColor="SkyBlue"
        ItemDisplayBinding="{Binding Name}"
        ItemsSource="{Binding Items}"
        TextColor="White" />
    <Label
        Margin="10"
        HorizontalTextAlignment="Center"
        Text="{Binding Source={x:Reference picker}, Path=SelectedItem.ID}"
        VerticalOptions="End" />
</HorizontalStackLayout>

MainViewModel.cs

using System.ComponentModel;
using System.Runtime.CompilerServices;

using Maui.ControlTest.Models;

namespace Maui.ControlTest.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> items;
        public List<ItemModel> Items
        {
            get
            {
                return items;
            }
            set
            {
                items = value;
                NotifyPropertyChanged();
            }
        }

        public MainViewModel()
        {
            List<ItemModel> itemModels = new List<ItemModel>();
            itemModels.Add(new ItemModel() { Name = "Korea", ID = 1 });
            itemModels.Add(new ItemModel() { Name = "Sudan", ID = 2 });
            itemModels.Add(new ItemModel() { Name = "United States", ID = 3 });
            itemModels.Add(new ItemModel() { Name = "Greece", ID = 4 });

            Items = itemModels;
        }
    }
}

ItemModel.cs

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

MVVM 실행결과

 

소스코드
https://github.com/kei-soft/KJunBlog/tree/master/Maui.ControlTest

 

KJunBlog/Maui.ControlTest 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