WPF 데이터 바인딩 완벽 정리
WPF(Windows Presentation Foundation)에서 데이터 바인딩(Data Binding)은 UI와 데이터 간의 연결을 설정하는 핵심 기능입니다.
1. WPF 데이터 바인딩이란?
데이터 바인딩을 사용하면 UI 요소와 데이터를 동기화할 수 있습니다. 코드 비하인드에서 직접 UI 요소를 변경하는 대신, 바인딩을 활용하여 데이터 변경 시 UI가 자동으로 업데이트됩니다.
🔹 주요 바인딩 모드
- OneWay: 데이터 변경 시 UI 업데이트 (기본값)
- TwoWay: UI와 데이터 간 동기화
- OneTime: 초기 로드 시 한 번만 바인딩
- OneWayToSource: UI에서 데이터로만 변경
2. OneWay 바인딩
데이터 변경 시 UI가 자동으로 업데이트되지만, UI에서 데이터를 변경해도 반영되지 않습니다.
<TextBlock Text="{Binding Name, Mode=OneWay}" />
OneWay 바인딩 예제
public class Person
{
public string Name { get; set; } = "홍길동";
}
3. TwoWay 바인딩
UI에서 변경한 값이 데이터에도 반영됩니다.
<TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
TwoWay 바인딩 예제
public class Person : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
4. INotifyPropertyChanged 인터페이스
INotifyPropertyChanged
는 바인딩된 속성이 변경될 때 UI에 알리는 역할을 합니다.
위 예제에서 OnPropertyChanged()
를 호출하면 UI가 자동으로 업데이트됩니다.
5. 실전 예제 - WPF 데이터 바인딩
아래는 WPF에서 TwoWay 데이터 바인딩을 적용한 예제입니다.
(1) Model - Person.cs
public class Person : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
(2) ViewModel - MainViewModel.cs
public class MainViewModel
{
public Person Person { get; set; }
public MainViewModel()
{
Person = new Person { Name = "홍길동" };
}
}
(3) View - MainWindow.xaml
<Window x:Class="WPFDataBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="데이터 바인딩 예제">
<Grid>
<TextBox Text="{Binding Person.Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Width="200" Height="30" />
</Grid>
</Window>
6. 마무리
이번 글에서는 WPF의 데이터 바인딩 개념과 주요 바인딩 모드를 정리했습니다.
- OneWay 바인딩은 데이터 → UI 방향
- TwoWay 바인딩은 데이터 ↔ UI 상호 변경
- INotifyPropertyChanged는 UI 자동 업데이트를 위해 필수
더 깊이 있는 내용을 배우고 싶다면 Microsoft 공식 WPF 데이터 바인딩 문서를 참고하세요!
'C#' 카테고리의 다른 글
C# WPF 스타일(Style)과 리소스(Resource) 사용법 (0) | 2025.03.28 |
---|---|
C#과 Google Vertex AI 통합 - AI 모델 구축 및 배포 (1) | 2025.03.27 |
C# LINQ 활용법 (0) | 2025.03.26 |
C# 성능 최적화, 메모리 관리, CPU 최적화, 비동기 프로그래밍, 성능 향상, .NET 성능, C# 최적화 전략 (0) | 2025.03.26 |
C# .NET 6 vs .NET Core (0) | 2025.03.26 |