VisualStudio/WPF

[WPF] RelayCommand

usingsystem 2023. 1. 4. 17:26
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