(자마린 데이터바인딩)Xamarin.Forms MVVM, ViewModel을 이용한 ListView 데이터 바인딩 예제_자마린교육추천/자마린실무학원 from 탑크리에듀(구로디지털단지역3번출구 2분거리)
(자마린 데이터바인딩)Xamarin.Forms MVVM, ViewModel을 이용한 ListView 데이터 바인딩 예제
n Model, ViewModel을 간단히 만들고 ViewModel을 ListView에 바인딩하는 간단한 예제를 작성해 보자.
n 사원의 사번과 이름을 입력하면 아래쪽 ListView에 바인딩되서 데이터가 뿌려지는 간단한 예제이다.
n Emp.cs
namespace DataBindingTest
{
class Emp
{
public string Empno { get; set; }
public string Ename { get; set; }
public bool IsChecked { get; set; }
}
}
n EmpViewModel.cs
using System.Collections.ObjectModel;
namespace DataBindingTest
{
class EmpViewModel
{
// Collection의 변화(Add/Delete)를 자동으로 감지하여 UI화면을 자동갱신
// ObservableCollection은 INotyfyChanged 인터페이스를 구현했다.
// ListView를 자동으로 업데이트 하기위해 ObservableCollection을 사용.
private ObservableCollection<Emp> emps = new ObservableCollection<Emp>();
public ObservableCollection<Emp> Emps
{
get
{
return emps;
}
set
{
emps = value;
}
}
public EmpViewModel()
{
Emps = new ObservableCollection<Emp>();
}
}
}
n MainPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
xmlns:local="clr-namespace:DataBindingTest"
x:Class="DataBindingTest.MainPage">
<Grid HorizontalOptions="Center">
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Label Text="사번" Grid.Row="0" Grid.Column="0" VerticalOptions="Center"/>
<Entry x:Name="txtEmpno" Grid.Row="0" Grid.Column="1" VerticalOptions="Center"/>
<Label Text="이름" Grid.Row="0" Grid.Column="2" VerticalOptions="Center"/>
<Entry x:Name="txtEname" Grid.Row="0" Grid.Column="3" VerticalOptions="Center"/>
<Button x:Name="btnSave" Text="저장" Grid.Row="1" Grid.ColumnSpan="4"
VerticalOptions="Center" Clicked="btnSave_Click"/>
<ListView x:Name="listView"
Grid.Row="3" Grid.ColumnSpan="4" VerticalOptions="Center">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.View>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Text="{Binding Empno}"></Label>
<Label Grid.Column="1" Text="{Binding Ename}"></Label>
<Switch Grid.Column="2" IsToggled="{Binding IsChecked}"></Switch>
</Grid>
</ViewCell.View>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</ContentPage>
n MainPage.xaml.cs
using System;
using Xamarin.Forms;
namespace DataBindingTest
{
public partial class MainPage : ContentPage
{
EmpViewModel viewModel = new EmpViewModel();
public MainPage()
{
InitializeComponent();
listView.ItemsSource = viewModel.Emps;
//BindingContext = viewModel;
}
private void btnSave_Click(object sender, EventArgs e)
{
viewModel.Emps.Add(new Emp() { Empno = txtEmpno.Text,
Ename =txtEname.Text,
IsChecked = false});
txtEmpno.Text = "";
txtEname.Text = "";
}
}
}
댓글 없음:
댓글 쓰기