[WPF] WPF 리스트 항목 데이터 바인딩 하는 방법

안녕하세요.

 

오늘은 WPF에서 데이터 바인딩에 대해서 공부 하려고 합니다.

 

그 중에서도, 리스트 항목을 데이터 바인딩 하는 방법에 대해서 알려 드리려고 하는데요.

 

일반 단일 항목을 바인딩 하는거랑 큰 차이는 없지만..공부를 하는 중이라 하나하나 모두 학습하는게 좋기 때문에 오늘은 리스트 항목을 데이터 바인딩해 보도록 하겠습니다.

 

그럼 바로 예제 코드를 작성해 보도록 하겠습니다.

 

 

Xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<Window x:Class="BindingTest.Window2"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BindingTest"
        mc:Ignorable="d"
        Title="Window2" Height="200" Width="400">
 
    <Window.Resources>
        <local:StudentList x:Key="stuList">
            <local:Student Name="범범조조" Age="12" PhoneNumber="000-1111-2222"/>
            <local:Student Name="아이유" Age="22" PhoneNumber="000-1111-2222"/>
            <local:Student Name="정형돈" Age="32" PhoneNumber="000-1111-2222"/>
            <local:Student Name="유새적" Age="42" PhoneNumber="000-1111-2222"/>
        </local:StudentList>
    </Window.Resources>
    
    <Grid DataContext="{StaticResource stuList}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
 
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
 
        <TextBlock Grid.Row="0" Grid.Column="0" Text="이름 : "
                   Margin="5"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"/>
        <TextBox Grid.Row="0" Grid.Column="1"
                 Margin="5"
                 Text="{Binding Path=Name}"/>
 
        <TextBlock Grid.Row="1" Grid.Column="0" Text="나이 : "
                   Margin="5"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"/>
        <TextBox Grid.Row="1" Grid.Column="1"
                 Margin="5"
                 Text="{Binding Path=Age}"/>
 
        <TextBlock Grid.Row="2" Grid.Column="0" Text="번호 : "
                   Margin="5"
                   VerticalAlignment="Center"
                   HorizontalAlignment="Center"/>
        <TextBox Grid.Row="2" Grid.Column="1"
                 Margin="5"
                 Text="{Binding Path=PhoneNumber}"/>
 
        <Grid Grid.Row="3" Grid.Column="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
 
            <Button x:Name="uiBtn_Pre" Grid.Column="0" Width="100" Height="25"  Margin="3" Content="이전"
                    Click="uiBtn_Pre_Click"/>
            <Button x:Name="uiBtn_Next" Grid.Column="1" Width="100" Height="25"  Margin="3" Content="다음"
                    Click="uiBtn_Next_Click"/>
        </Grid>
    </Grid>
</Window>
 
cs

 

비하인드 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
 
namespace BindingTest
{
    /// <summary>
    /// Window2.xaml에 대한 상호 작용 논리
    /// </summary>
    public partial class Window2 : Window
    {
        public Window2()
        {
            InitializeComponent();
        }
 
        /// <summary>
        /// 이전 목록 리스트 변경 이벤트 핸들러
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiBtn_Pre_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView view = GetList();
 
            view.MoveCurrentToPrevious();
 
            if (view.IsCurrentBeforeFirst)
            {
                view.MoveCurrentToFirst();
            }
        }
 
        /// <summary>
        /// 다음 목록 리스트 변경 이벤트 핸들러
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiBtn_Next_Click(object sender, RoutedEventArgs e)
        {
            ICollectionView view = GetList();
 
            view.MoveCurrentToNext();
 
            if (view.IsCurrentAfterLast)
            {
                view.MoveCurrentToLast();
            }
        }
 
        private ICollectionView GetList()
        {
            StudentList list = (StudentList)this.FindResource("stuList");
 
            return CollectionViewSource.GetDefaultView(list);
        }
    }
}
 
cs

 

Student.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System.ComponentModel;
 
namespace BindingTest
{
    public class Student :INotifyPropertyChanged
    {
        /// <summary>
        /// this 생성자
        /// </summary>
        public Student() : this("범범조조""28""000-1111-2222") { }
 
        public Student(string name, string age, string number)
        {
            this.Name = name;
            this.Age = age;
            this.PhoneNumber = number;
        }
 
        private string name;
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
                OnPropertyChanged("Name");
            }
        }
 
        private string age;
        public string Age
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
                OnPropertyChanged("Age");
            }
        }
 
        private string phoneNumber;
 
        public string PhoneNumber
        {
            get
            {
                return phoneNumber;
            }
            set
            {
                phoneNumber = value;
                OnPropertyChanged("PhoneNumber");
            }
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
 
        void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(thisnew PropertyChangedEventArgs(propertyName));
        }
    }
}
 
cs

 

StudentList.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace BindingTest
{
    public class StudentList : List<Student>
    {
    }
}
 
cs

 

실행 결과

 

위와 같이 StudentList에 여러 학생의 데이터를 넣고 바인딩 시키고, 다음 버튼과 이전 버튼을 클릭했을 때 전 후의 리스트 데이터들이 알맞게 표시되는 것을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY