728x90
반응형

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

728x90
반응형
Posted by kjun

댓글을 달아 주세요