C#, WPF Command 패턴 HelloWorld, 데이터바인딩
n WPF의 명령(Command)은 ICommand 인터페이스를 구현하여 만들며 IComand는 Execute 및 CanExecute라는 두 가지 메서드와 CanExecuteChanged 이벤트를 제공한다.
n Execute 메서드는 실제 처리해야 하는 작업을 기술하고 CanExecute 메소드에서는 Execute 메소드의 코드를 실행할지 여부를 결정하는 코드를 기술한다. CanExecute가 false를 리턴하면 Execute 메소드는 호출되지 않는다.
n 즉 CanExecute 메소드는 명령을 사용 가능하게 하거나 사용 불가능하게 할 때 사용되며 명령을 사용할 수 있는지 여부를 확인하기 위해 WPF에 의해 호출된다. 이 메소드는 키보드 GET포커스, LOST포커스, 마우스 업 등과 같은 UI 상호 작용 중에 대부분 발생한다.
n CanExecute 메소드가 호출되어 CanExecute의 상태가 변경되면 CanExecuteChanged 이벤트가 발생해야 하며, WPF는 CanExecute를 호출하고 Command에 연결된 컨트롤의 상태를 변경한다.
n 1. View(MainWindow.xaml)
<Window x:Class="MVVMTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MVVMTest"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="400">
<Window.DataContext>
<local:MainWindowViewModel/>
</Window.DataContext>
<Grid>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="62,45,0,0" TextWrapping="Wrap"
Text="" VerticalAlignment="Top" Width="126"/>
<Button Content="Click"
Height="23"
HorizontalAlignment="Left"
Margin="193,45,0,0"
Name="btnClick"
VerticalAlignment="Top"
Width="87"
Command="{Binding ButtonCommand}"
CommandParameter="{Binding Text, ElementName=textBox}" />
</Grid>
</Window>
n 2. ViewModel(C# 클래스)- ViewModel에서 RelayCommand를 통해 메시지박스를 띄움
using System;
using System.Windows.Input;
using System.Windows;
namespace MVVMTest
{
class MainWindowViewModel
{
private ICommand m_ButtonCommand;
public ICommand ButtonCommand
{
get
{
return m_ButtonCommand;
}
set
{
m_ButtonCommand = value;
}
}
public MainWindowViewModel()
{
//ButtonCommand = new RelayCommand(new Action<object>(ShowMessage));
ButtonCommand = new RelayCommand(ShowMessage);
}
public void ShowMessage(object param)
{
MessageBox.Show("Hi~ " + param.ToString());
} }
}
n ICommand를 상속받은 RelayCommand.cs
using System;
using System.Windows.Input;
namespace MVVMTest
{
class RelayCommand : ICommand
{
private Action<object> _action;
public RelayCommand(Action<object> action)
{
_action = action;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_action(parameter);
}
#endregion
}
}
Command vs Click Event
- Command는 Caller(버튼, Invoker)와 연결되어 있지 않으므로 동일한 Command가 메뉴 항목, 도구 모음 버튼, 키보드 등에서 호출 가능
- Command는 명령 상태에 따라 관련된 모든 UI 컨트롤을 활성화 / 비활성화 할 수 있도록 지원(실행 가능 또는 불가능)
댓글 없음:
댓글 쓰기