728x90
- RelayCommand 스크립트 생성 ICommand 상속 받기
public class RelayCommand<T> : ICommand
{
readonly Predicate<T> _canExecute;
readonly Action<T> _execute;
public RelayCommand(Action<T> action, Predicate<T> predicate)
{
_execute = action;
_canExecute = predicate;
}
public RelayCommand(Action<T> action) : this(action, null)
{
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute.Invoke((T)parameter);
}
public void Execute(object parameter)
{
_execute.Invoke((T)parameter);
}
}
- ViewModel 스크립트에 ICommand 등록
public class Window1ViewModel : INotifyPropertyChanged
{
public ICommand TestClick { get; set; }
public Window1ViewModel()
{
TestClick = new RelayCommand<object>(ExecuteMyButton);
}
void ExecuteMyButton(object param)
{
MessageBox.Show("zz");
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
- View 스크립트에 ViewModel 연결
public partial class Window1 : Window
{
Window1ViewModel _window1ViewModel;
public Window1()
{
InitializeComponent();
_window1ViewModel = new Window1ViewModel();
DataContext= _window1ViewModel;
}
}
- xaml에 ViewMdel 바인딩
<Grid>
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="243,178,0,0" VerticalAlignment="Top"
Command="{Binding TestClick}"/>
</Grid>
728x90
'VisualStudio > WPF' 카테고리의 다른 글
[WPF] 다양한이벤트처리방법 Nuget XamlBehaviorsWpf (0) | 2023.01.05 |
---|---|
[WPF] 사용자 정의컨트롤 디펜던시프로퍼티(DependencyProperty) (0) | 2023.01.05 |
[WPF] Async RelayCommand 사용 방법 (0) | 2023.01.05 |
[WPF] INotifyPropertyChanged사용 하여 MVVM 만들기 (0) | 2023.01.04 |
[WPF] Window.Resources 사용법 (0) | 2023.01.04 |