프로그래밍/c# wpf

WPF에서 MVVM 패턴과 DataContext 설정 가이드

rrruu 2025. 6. 20. 16:51
반응형

WPF(Windows Presentation Foundation)는 강력한 데이터 바인딩(DataBinding) 기능을 제공하는 UI 프레임워크입니다. MVVM(Model-View-ViewModel) 패턴을 적용하면 UI(View), 비즈니스 로직(ViewModel), 데이터(Model) 간의 결합도를 낮춰 유지보수성과 테스트 가능성을 높일 수 있습니다. 이 글에서는 특히 DataContext를 통해 View와 ViewModel을 연결하는 5가지 방법을 코드를 통해 자세히 알아봅니다.


MVVM 패턴 핵심 요소

  1. Model
    • 도메인 데이터와 비즈니스 로직을 표현
  2. ViewModel
    • INotifyPropertyChanged 구현
    • View에 바인딩할 속성(Property)과 명령(ICommand)을 정의
  3. View
    • XAML 기반 UI
    • {Binding} 문법으로 ViewModel의 속성/명령 연결

DataContext란 무엇인가?

  • DataContext는 WPF에서 Binding의 기본 데이터 소스 역할
  • View의 최상위 요소(Window, UserControl 등)에 설정
  • 하위 컨트롤들은 별도 지정 없이 부모의 DataContext를 상속
<!-- MainWindow.xaml -->
<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        Title="MVVM DataContext 예제"
        Width="600" Height="400">
    <Grid>
        <TextBlock Text="{Binding Greeting}" FontSize="24" />
        <Button Content="클릭" Command="{Binding ClickCommand}" />
    </Grid>
</Window>

 

1. 코드비하인드에서 직접 할당

가장 직관적이지만 View-ViewModel 결합도가 높아지는 방식입니다.

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new MainViewModel();
    }
}

 

 

  • 장점: 구현이 간단하고 바로 확인 가능
  • 단점: 테스트 어려움, View 수정 시 코드비하인드 의존성 증가

2. App.xaml 리소스에서 StaticResource 사용

App.xaml에 ViewModel을 전역 리소스로 등록 후 XAML에서 참조합니다.

<!-- App.xaml -->
<Application.Resources>
    <vm:MainViewModel x:Key="MainVM" />
</Application.Resources>

<!-- MainWindow.xaml -->
<Window DataContext="{StaticResource MainVM}"
        xmlns:vm="clr-namespace:MyApp.ViewModels">
    <!-- UI 구성 -->
</Window>

 

 

 

  • 장점: XAML만으로 DataContext 설정
  • 단점: 애플리케이션 전체에서 동일 인스턴스 공유

3. ViewModelLocator 패턴 적용

ViewModelLocator 클래스로 ViewModel 생성 로직을 중앙집중화합니다.

// ViewModelLocator.cs
public class ViewModelLocator
{
    public MainViewModel MainVm { get; } = new MainViewModel();
}

// App.xaml
<Application.Resources>
    <local:ViewModelLocator x:Key="Locator" />
</Application.Resources>

 

 

<!-- MainWindow.xaml -->
<Window DataContext="{Binding MainVm, Source={StaticResource Locator}}"
        xmlns:local="clr-namespace:MyApp">
    <!-- UI 구성 -->
</Window>

 

 

  • 장점: DI 컨테이너 연동, 팩토리 패턴 적용 용이
  • 단점: Locator 클래스 작성 필요

프로젝트 규모와 요구사항에 맞는 방식을 선택하여 적용하면, WPF 애플리케이션의 구조화와 유지보수 효율을 크게 향상시킬 수 있습니다. 간단한 소규모 프로젝트라면 코드비하인드나 StaticResource 방식을, 확장성과 테스트가 중요한 중대형 애플리케이션에는 ViewModelLocator나 DI 컨테이너 기반 설정을 고려해 보세요. 올바른 DataContext 설정은 바인딩 안정성과 코드 가독성을 높여, 개발 생산성과 품질을 동시에 끌어올립니다. 적합한 접근 방식을 선택해 깔끔하고 견고한 MVVM 구조를 완성해 보시기 바랍니다.

 

반응형