본문 바로가기
WPF

WPF DataGrid에 데이터 바인딩하기

by 개발하는 늑대 2025. 3. 6.
728x90

WPF DataGrid에 데이터 바인딩 쉽게 해보기

안녕하세요, 여러분! 지난번에 텍스트 박스와 버튼으로 WPF 바인딩의 기본을 배웠다면, 이번에는 한 단계 더 나아가 DataGrid에 데이터를 바인딩하는 방법을 알아볼게요. DataGrid는 테이블 형태로 데이터를 보여줄 때 정말 유용한 컨트롤이에요. 이번 예제에서는 학생 목록을 표시하고, 사용자가 새 학생을 추가할 수 있는 기능을 만들어 보겠습니다. 바로 시작해볼까요?

완성 모습 미리보기

이번 예제에서 만들어볼 결과물은:

  • DataGrid에 학생 이름과 나이를 표시해요.
  • 텍스트 박스에 이름과 나이를 입력하고 버튼을 누르면 목록에 추가돼요.

간단하지만 실무에서도 자주 쓰이는 패턴이에요. 그럼 코드로 들어가 볼게요!

1. XAML 코드 작성하기

먼저 MainWindow.xaml에 아래 코드를 넣어주세요.

<Window x:Class="WpfDataGridExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF DataGrid 바인딩 예제" Height="350" Width="500">
    <Grid Margin="10">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0,0,0,10">
            <TextBlock Text="이름:" Margin="0,0,5,0"/>
            <TextBox x:Name="NameTextBox" Width="100" Margin="0,0,10,0"/>
            <TextBlock Text="나이:" Margin="0,0,5,0"/>
            <TextBox x:Name="AgeTextBox" Width="50" Margin="0,0,10,0"/>
            <Button Content="추가" Width="80" Click="AddButton_Click"/>
        </StackPanel>

        <DataGrid Grid.Row="1" x:Name="StudentDataGrid" AutoGenerateColumns="False" ItemsSource="{Binding Students}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="이름" Binding="{Binding Name}" Width="*"/>
                <DataGridTextColumn Header="나이" Binding="{Binding Age}" Width="100"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

코드 설명

  • : Grid를 두 행으로 나눴어요. 위쪽은 입력 영역, 아래쪽은 DataGrid가 들어갈 공간이에요.
  • : 이름과 나이를 입력할 텍스트 박스와 추가 버튼을 가로로 배치했어요.
  • :
    • AutoGenerateColumns="False": 열을 자동 생성하지 않고 직접 정의할 거예요.
    • ItemsSource="{Binding Students}": Students라는 데이터 소스에 바인딩해요.
    • : "이름"과 "나이" 열을 정의하고, 각각 NameAge 속성에 바인딩했어요.

2. C# 코드 작성하기

이제 데이터와 로직을 담당할 MainWindow.xaml.cs에 아래 코드를 넣어주세요.

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace WpfDataGridExample
{
    public partial class MainWindow : Window
    {
        public ObservableCollection Students { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            Students = new ObservableCollection
            {
                new Student { Name = "홍길동", Age = 20 },
                new Student { Name = "김영희", Age = 22 }
            };
            DataContext = this; // 이 창을 데이터 소스로 설정
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(NameTextBox.Text) && int.TryParse(AgeTextBox.Text, out int age))
            {
                Students.Add(new Student { Name = NameTextBox.Text, Age = age });
                NameTextBox.Clear();
                AgeTextBox.Clear();
            }
            else
            {
                MessageBox.Show("이름과 나이를 올바르게 입력해주세요!");
            }
        }
    }

    public class Student : INotifyPropertyChanged
    {
        private string _name;
        private int _age;

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged(nameof(Name));
            }
        }

        public int Age
        {
            get { return _age; }
            set
            {
                _age = value;
                OnPropertyChanged(nameof(Age));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

코드 설명

  • ObservableCollection: 데이터 목록을 저장하는 컬렉션이에요. 이 클래스는 데이터가 추가되거나 삭제될 때 UI에 자동으로 반영돼요.
  • Student 클래스:
    • NameAge 속성을 정의했어요.
    • INotifyPropertyChanged: 속성 값이 바뀔 때 UI에 알리는 인터페이스예요.
  • MainWindow 생성자: 초기 데이터(홍길동, 김영희)를 추가하고, DataContext를 설정했어요.
  • AddButton_Click: 버튼 클릭 시 입력값을 확인한 후 Students에 새 학생을 추가해요.

3. 바인딩 동작 이해하기

이제 어떻게 작동하는지 단계별로 볼게요:

  1. 프로그램이 시작되면 Students에 초기 데이터가 표시돼요.
  2. 사용자가 이름과 나이를 입력하고 "추가" 버튼을 누르면, ObservableCollection에 새 항목이 추가되면서 DataGrid가 자동으로 갱신돼요.
  3. INotifyPropertyChanged 덕분에 개별 학생 데이터가 바뀌어도 UI에 반영돼요(이번 예제에서는 사용하지 않았지만 확장 가능).

4. 실행해보기

  1. Visual Studio에서 새 WPF 프로젝트를 만드세요.
  2. MainWindow.xamlMainWindow.xaml.cs에 위 코드를 붙여넣으세요.
  3. 빌드하고 실행하면 학생 목록이 표시되고, 새 학생을 추가할 수 있어요!

실행 결과

  • 초기 화면에 "홍길동(20)"과 "김영희(22)"가 표시돼요.
  • 이름에 "이철수", 나이에 "25"를 입력하고 추가하면 테이블에 새 행이 추가돼요.

5. DataGrid 바인딩의 장점

  • 자동 갱신: ObservableCollection 덕분에 데이터가 바뀌면 UI가 바로 반영돼요.
  • 유연성: 열을 커스터마이징해서 원하는 대로 표시할 수 있어요.
  • 확장성: 데이터베이스나 외부 소스와 연결하기도 쉬워요.

마무리

WPF의 DataGrid로 데이터 바인딩을 해봤어요! 이 예제를 기반으로 컬럼을 더 추가하거나, 삭제 버튼을 넣는 등 확장해보세요. 질문이 있으면 댓글로 남겨주시고, 다음에 더 유용한 WPF 팁으로 찾아올게요. 즐거운 코딩 되세요! 😊

728x90