내가 보고 이해하기위해 작성하는 글
버튼 의 클릭이벤트 등을 ViewModel에서 관리하여 유지보수에 용의하게 하기위해 사용
보통 클릭이벤트를 만들경우 비하인드 에 click이벤트가 만들어지면서 작성하게되지만
ICommand를 사용하게된다면 Command에 바인딩을 진행해서 ViewModel에서 사용되게 할수있다.
오늘은 기본적인 사용법만 알아 보려고 한다.
RelayCommand 라는 폴더여도 좋고 그냥 Command 라는 폴더여도 상관없다.
파일은 RelayCommand로 지어놓았다.
ButtonClick 이벤트를 만들 ViewModel을 만든다.
ViewModel로 컨트롤 할 UI 파일을 만든다.
이렇게 3가지를 준비하고 조합해주면되는대.
필자는 아직 이해하지못하였고 , 사용법만 숙지한 상태이다.
사용하기위해서는 RelayCommand.cs 파일에 내용을 넣어주어야한다.
아래의 코드를 보면
CanExecuteChanged 이벤트가 발생하면 CanExecute를 통해 컨트롤이 사용가능한지 체크하고 IsEnable 속성을 업데이트합니다. IsEnable이 적용되는 컨트롤은 ButtonBase, MenuItem, Hyperlink 등이 있습니다.
사용자 명령이 발생하면 IsEnable이 true로 활성화된 컨트롤은 Execute에 정의된 동작이 실행됩니다.
참조 : https://endtime-co-kr.tistory.com/entry/RelayCommand-ICommand
using System;
using System.Windows.Input;
namespace SCHScheduler.RelayCommand
{
public class RelayCommands : ICommand
{
private readonly Action _execute;
private readonly Func<bool> _canExecute;
public RelayCommands(Action execute, Func<bool> canExecute = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute();
}
public void Execute(object parameter)
{
_execute();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
}
위의 코드는 저렇게 동작하게하는 매서드같은거다 정도로 이해하는중입니다.
아래의 코드에서 날짜를 추가하고 빼는 함수입니다.
using SCHScheduler.RelayCommand;
using System;
using System.ComponentModel;
using System.Windows.Input;
namespace SCHScheduler.ViewModel
{
public class CurrentTimeViewModel : INotifyPropertyChanged
{
private DateTime _currentDate;
public CurrentTimeViewModel()
{
_currentDate = DateTime.Now;
UpdateDate(); // 초기 날짜 및 시간 설정
}
public DateTime CurrentDate
{
get => _currentDate;
private set
{
if (_currentDate != value)
{
_currentDate = value;
OnPropertyChanged(nameof(CurrentDate));
OnPropertyChanged(nameof(CurrentDateString)); // 날짜 문자열 프로퍼티도 갱신
}
}
}
// 날짜만 문자열로 반환하는 프로퍼티
public string CurrentDateString => _currentDate.ToString("yyyy-MM-dd");
public void UpdateDate()
{
CurrentDate = DateTime.Now; // 현재 날짜 및 시간 설정
}
// 주의깊게 볼 코드
public void AddOneDay()
{
CurrentDate = CurrentDate.AddDays(1); // 하루 추가
}
public void SubtractOneDay()
{
CurrentDate = CurrentDate.AddDays(-1); // 하루 감소
}
public ICommand AddDayCommand => new RelayCommands(AddOneDay);
public ICommand SubtractDayCommand => new RelayCommands(SubtractOneDay);
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
1.버튼을 Command 에 바인딩해서 사용한다.
2.위의 주의깊게 볼 코드 부분에 RelayCommnds 부분은 확인한ㄷ.
3. 저렇게 얽혀서 사용할수있게 하는부분이다.
4. 위의 코드는 날짜를 더하고 빼는 기능이다.
<Button
x:Name="xButtonPreDay"
Grid.Column="1"
Height="40"
Margin="2"
Background="Transparent"
BorderBrush="Transparent"
Command="{Binding SubtractDayCommand}"
Click="xButtonPreDay_Click">
추후 더 사용해보면서 정리해보겟습니다.