C# WPF/WinForms GUI 개발: MVVM, 데이터 바인딩, 커스텀 컨트롤 활용
C#에서 GUI 애플리케이션 개발은 WPF(Windows Presentation Foundation)와 WinForms 두 가지 주요 기술을 통해 이루어집니다.
사용자 인터페이스(UI) 구성, 이벤트 처리, 화면 전환 등 다양한 기능을 효율적으로 구현하려면 MVVM 패턴, 데이터 바인딩, 커스텀 컨트롤 활용이 필수적입니다.
이번 글에서는 실무 예제와 함께 WPF/WinForms GUI 개발 핵심 개념과 구현 방법을 소개합니다.
1. WPF와 WinForms 비교
- WinForms: 빠른 UI 구성, 단순한 이벤트 기반, 레거시 프로젝트 활용
- WPF: XAML 기반, MVVM 패턴, 데이터 바인딩 지원, UI 커스터마이징 용이
새로운 프로젝트에서는 유지보수성과 확장성을 고려해 WPF + MVVM 조합을 권장합니다.
2. MVVM 패턴 이해
MVVM(Model-View-ViewModel) 패턴은 UI(View)와 비즈니스 로직(ViewModel) 분리를 목표로 합니다.
데이터 바인딩과 명령(Command)을 활용하면 UI 이벤트 처리와 로직을 깔끔하게 분리할 수 있습니다.
// Model
public class Person {
public string Name { get; set; }
public int Age { get; set; }
}
// ViewModel
using System.ComponentModel;
using System.Windows.Input;
public class PersonViewModel : INotifyPropertyChanged {
private Person _person = new Person();
public string Name {
get => _person.Name;
set { _person.Name = value; OnPropertyChanged(nameof(Name)); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string prop) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(prop));
}
// Command 예제
public ICommand GreetCommand => new RelayCommand(() =>
Console.WriteLine($"Hello, {Name}")
);
}
3. 데이터 바인딩
WPF에서는 XAML과 ViewModel을 연결하여 자동 UI 갱신이 가능합니다.
UI 요소 변경 시 ViewModel 값이 자동으로 반영되고, 반대로 코드 변경 시 UI도 업데이트됩니다.
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MVVM Example" Height="200" Width="300">
<StackPanel Margin="20">
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<Button Content="Greet" Command="{Binding GreetCommand}" />
</StackPanel>
</Window>
4. 커스텀 컨트롤
WPF에서는 기존 컨트롤을 상속하거나 UserControl을 만들어 재사용 가능한 UI 컴포넌트를 생성할 수 있습니다.
// UserControl 예제
public partial class PersonControl : UserControl {
public PersonControl() {
InitializeComponent();
}
public string PersonName {
get { return (string)GetValue(PersonNameProperty); }
set { SetValue(PersonNameProperty, value); }
}
public static readonly DependencyProperty PersonNameProperty =
DependencyProperty.Register("PersonName", typeof(string), typeof(PersonControl), new PropertyMetadata(""));
}
5. UI 이벤트 처리와 화면 전환
- Button 클릭, TextBox 입력 등 이벤트 처리 → MVVM에서는 Command 사용
- 화면 전환 → NavigationService 또는 Frame 컨트롤 활용
- 동적 UI 변경 → ObservableCollection과 INotifyPropertyChanged 결합
6. 실무 활용 팁
- MVVM 패턴 적용 → 코드 유지보수 용이, UI와 로직 분리
- DataTemplate 활용 → 다양한 UI 표현, 재사용성 증가
- 비동기 작업 → UI 블로킹 방지 (async/await)
- 커스텀 컨트롤 → 반복되는 UI 구성 최소화
- ViewModel 설계 시 단일 책임 원칙(SRP) 적용
마무리
C# WPF/WinForms GUI 개발에서는 MVVM 패턴과 데이터 바인딩, 커스텀 컨트롤을 적절히 활용하면
유지보수성과 확장성 높은 UI를 구현할 수 있습니다.
이벤트 처리와 화면 전환 기능까지 결합하면 실무 프로젝트에서 효율적이고 반응성이 뛰어난 애플리케이션을 만들 수 있습니다.
'c#' 카테고리의 다른 글
C# 비동기 프로그래밍: async/await와 Task 활용 (0) | 2025.09.21 |
---|---|
C# LINQ 활용법 – 컬렉션 처리와 데이터 쿼리 (0) | 2025.09.21 |
C# Entity Framework(Core)와 데이터베이스 연동 (1) | 2025.09.18 |
C# 디자인 패턴 – Singleton, Factory, Observer 사용법 (0) | 2025.09.18 |
.NET Task.Run 사용법: 비동기 프로그래밍을 시작하는 가장 쉬운 방법 (0) | 2025.09.11 |