DialogService를 이용하면 MVVM 패턴에서 ViewModel과 View 간의 의존성을 줄이면서도 깔끔하게 MessageBox와 같은 다이얼로그를 처리할 수 있습니다. 아래는 DialogService를 구현하고 사용하는 예입니다:
1. DialogService 인터페이스 정의
먼저, 다이얼로그 동작을 추상화하는 인터페이스를 정의합니다.
public interface IDialogService
{
void ShowMessage(string message, string title);
}
2. DialogService 구현
인터페이스를 실제로 구현하여 MessageBox를 호출하는 클래스를 작성합니다.
using System.Windows;
public class DialogService : IDialogService
{
public void ShowMessage(string message, string title)
{
MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Information);
}
}
3. ViewModel에서 DialogService 사용
ViewModel에서는 IDialogService를 의존성 주입(Dependency Injection) 받아 사용합니다.
public class MyViewModel
{
private readonly IDialogService _dialogService;
public MyViewModel(IDialogService dialogService)
{
_dialogService = dialogService;
}
public void ShowInfoCommand()
{
_dialogService.ShowMessage("안녕하세요! MVVM에서 MessageBox를 호출합니다.", "알림");
}
}
4. Application에서 Service를 주입
WPF 프로젝트의 Application 또는 MainWindow 코드에서 DialogService를 ViewModel에 주입합니다.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
IDialogService dialogService = new DialogService();
DataContext = new MyViewModel(dialogService); // 주입
}
}
5. XAML에서 Command Binding
View에서 ShowInfoCommand를 바인딩합니다.
<Button Content="Show Message"
Command="{Binding ShowInfoCommand}" />
핵심 장점
- 테스트 가능성: ViewModel을 독립적으로 테스트할 수 있습니다. 예를 들어, 테스트 프로젝트에서 MockDialogService를 만들어 ViewModel을 단위 테스트할 수 있습니다.
- MVVM 원칙 준수: ViewModel이 UI 요소(MessageBox)에 직접 의존하지 않아 패턴의 구조적 장점이 유지됩니다.
- 유연성: ViewModel이 다양한 형태의 다이얼로그 또는 알림을 호출하도록 쉽게 확장할 수 있습니다.
LIST
'WPF' 카테고리의 다른 글
WPF TreeViewItem Font 스타일 변경 방법 (0) | 2025.04.23 |
---|---|
WPF MVVM에서 Window Close 호출 방법 (0) | 2025.04.23 |
WPF MVVM 패턴을 이용한 프로그램에서 Messagebox를 실행할 경우 호출 스택에서 throw 발생하는 경우 (0) | 2025.04.23 |
WPF Group에서 Category 또는 Group별로 표시 하는 방법 (1) | 2025.04.23 |
WPF MVVM TextBlock Foreground Binding (0) | 2023.06.16 |