728x90
반응형

WPF - Commands
WPF의 Command 시스템은 버튼 클릭 등 UI 이벤트를 코드와 분리하여 재사용 가능하게 만들어주는 강력한 구조이며,
MVVM 패턴의 핵심 도구이다.
Commands?
- WPF에서 버튼 클릭같은 사용자 동작을 처리하는 추상화된 방법
- 기존 이벤트 핸들러(Click 등) 보다 더 재사용 가능, 중앙 집중적, 테스트 용이
- 기본적으로 ICommand 인터페이스를 구현함
| 구성 요소 | 설명 |
| ICommand | 명령을 표현하는 인터페이스 (Execute, CanExecute, CanExecuteChanged) |
| RoutedCommand | UI 트리 내에서 전달 가능한 커맨드 |
| CommandBinding | 특정 커맨드를 실제 로직과 연결 |
| Button.Command | 커맨드를 사용하는 UI 요소 |
1. 기본 RoutedCommand 예제
//cs
public partial class MainWindow : Window
{
public static RoutedCommand MyCommand = new RoutedCommand();
public MainWindow()
{
InitializeComponent();
// 커맨드 실행과 가능여부 연결
CommandBindings.Add(new CommandBinding(MyCommand, ExecuteCommand, CanExecuteCommand));
}
private void ExecuteCommand(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("커맨드 실행됨!");
}
private void CanExecuteCommand(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true; // 조건에 따라 false도 가능
}
}
//xaml
<Button Content="실행" Command="{x:Static local:MainWindow.MyCommand}" />
xaml에서 선언하기
<Window ... xmlns:local="clr-namespace:YourNamespace">
<Window.CommandBindings>
<CommandBinding Command="{x:Static local:MainWindow.MyCommand}"
Executed="MyCommand_Executed"
CanExecute="MyCommand_CanExecute" />
</Window.CommandBindings>
<StackPanel>
<Button Command="{x:Static local:MainWindow.MyCommand}" Content="실행" />
</StackPanel>
</Window>
2. built-in commands (내장 명령어)
| 커맨드 | 설명 |
| ApplicationCommands.Copy | 복사 |
| ApplicationCommands.Paste | 붙여넣기 |
| NavigationCommands.BrowseBack | 뒤로가기 |
| MediaCommands.Play | 미디어 재생 |
단, CommandBinding을 연결하지 않으면 작동하지 않음
<Button Command="ApplicationCommands.Copy" Content="복사" />
3. keybinding (단축키 연결)
<Window.InputBindings>
<KeyBinding Command="{x:Static local:MainWindow.MyCommand}" Key="F5" />
</Window.InputBindings>
4. MVVM에서 ICommand 사용하기 (DelegateCommand or RelayCommand)
1) 커맨드 클래스 만들기
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);
public void Execute(object parameter) => _execute(parameter);
public event EventHandler CanExecuteChanged
{
add => CommandManager.RequerySuggested += value;
remove => CommandManager.RequerySuggested -= value;
}
}
2) ViewModel에서 ICommand 프로퍼티 선언
public class MyViewModel
{
public ICommand SayHelloCommand { get; }
public MyViewModel()
{
SayHelloCommand = new RelayCommand(p => MessageBox.Show("안녕하세요!"));
}
}
3) XAML에서 바인딩
View의 DataContext는 MyViewModel로 설정되어 있어야 함
<Button Content="인사하기" Command="{Binding SayHelloCommand}" />'프로그래밍&IT > C# (Winfrom, WPF)' 카테고리의 다른 글
| [WPF] Styles and Behaviors (1) | 2025.08.09 |
|---|---|
| [WPF] Resources (3) | 2025.08.07 |
| [WPF] Element Binding (4) | 2025.08.04 |
| [WPF] The Application (1) | 2025.08.04 |
| [WPF] Controls (3) | 2025.08.04 |