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>
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; }
}
}
소스코드
https://github.com/kei-soft/KJunBlog/tree/master/Maui.ControlTest
728x90
'C# > Xamarin Maui' 카테고리의 다른 글
[.NET MAUI] TableView 사용하기 (0) | 2022.09.15 |
---|---|
[.NET MAUI] 화면 Capture 하기 - ScreenShot (0) | 2022.09.15 |
[.NET MAUI] Circle Image 표시 하기 (2가지 방법) (0) | 2022.09.14 |
[.NET MAUI] CommunityToolkit.Maui Toast Message (0) | 2022.09.14 |
[.NET MAUI] CommunityToolkit.Maui Snackbar (0) | 2022.09.14 |