[WPF] WPF DataGrid 컨트롤 MVVM 패턴 데이터 바인딩하기

안녕하세요.

 

오늘은 WPF에서 DataGird 컨트롤을 MVVM 패턴을 이용하여 데이터 바인딩 하는 방법에 대해서 알려드리려고 합니다.

 

저도 최근에 계속 WPF를 독학으로 공부하는 중이라서, 향후에 저처럼 힘들게 시간낭비를 하시는 분들에게 조금의 도움이 되고자 정보를 남기려고 합니다ㅎㅎ

 

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

 

 

MainWindow.xaml
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
<Window x:Class="DataGridTest.MainWindow"
        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:DataGridTest"
        xmlns:vm ="clr-namespace:DataGridTest.ViewModel"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="400">
    <Window.DataContext>
        <vm:MainWindowViewModel/>
    </Window.DataContext>
    
    <Grid>
        <DataGrid x:Name="uiGrid_Main" Grid.ColumnSpan="3" Margin="5"
                  AutoGenerateColumns="False"
                  ItemsSource="{Binding Path= SampleDatas, Mode=TwoWay, 
            NotifyOnSourceUpdated=True, NotifyOnTargetUpdated=True}">
            <DataGrid.Columns>
                <DataGridTextColumn MinWidth="10" Width="Auto" Header="NAME" Binding="{Binding Name}"/>
                <DataGridTextColumn MinWidth ="100" Width="Auto" Header="AGE" Binding="{Binding Age}"/>
                <DataGridTextColumn MinWidth="100" Width="Auto" Header="GRADE" Binding="{Binding Grade}"/>
                <DataGridTextColumn MinWidth="200" Width="*" Header="SCORE" Binding="{Binding Score}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>
 
cs

 

BaseVM.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System.ComponentModel;
 
namespace DataGridTest.ViewModel
{
    public class BaseVM : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
 
        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(thisnew PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
 
cs

 

StudentModel.cs
1
2
3
4
5
6
7
8
9
10
11
namespace DataGridTest.Model
{
    public class StudentModel
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Grade { get; set; }
        public int Score { get; set; }
    }
}
 
cs

 

MainWindowViewModel.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
using DataGridTest.Model;
using System.Collections.ObjectModel;
 
namespace DataGridTest.ViewModel
{
    public class MainWindowViewModel : BaseVM
    {
        StudentModel stu = null;
 
        public MainWindowViewModel()
        {
            stu = new StudentModel();
            AddStudent();
        }
 
        ObservableCollection<StudentModel> _sampleDatas = null;
        public ObservableCollection<StudentModel> SampleDatas
        {
            get
            {
                if (_sampleDatas == null)
                {
                    _sampleDatas = new ObservableCollection<StudentModel>();
                }
                return _sampleDatas;
            }
            set
            {
                _sampleDatas = value;
            }
        }
 
        /// <summary>
        /// 학생 추가
        /// </summary>
        public void AddStudent()
        {
            StudentModel sut = new StudentModel();
            stu.Name = "범범조조";
            stu.Age = 29;
            stu.Score = 100;
            stu.Grade = "A";
 
            SampleDatas.Add(stu);
        }
    }
}
 
cs

 

실행 결과

이와 같이 Student 학생 객체를 생성하고 그 객체가 DataGrid에 바인딩 되어 출력된 것을 확인하실 수 있습니다.

 

감사합니다.^^

728x90

이 글을 공유하기

댓글

Designed by JB FACTORY