WPF DelegateCommand RelayCommand ViewModel------绝对正确

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfApp10
{
  
    public class DelegateCommand : ICommand
    {
        Func<object, bool> canExecute;
        Action<object> executeAction;

        public DelegateCommand(Action<object> executeAction, Func<object, bool> canExecute)
        {
            this.executeAction = executeAction;
            this.canExecute = canExecute;
        }

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            if (canExecute == null)
            {
                return true;
            }
            return canExecute.Invoke(parameter);
        }

        //public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            executeAction(parameter);
        }
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        #endregion
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace WpfApp10
{
    public class ViewMode : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _msg = "";

        public string Message
        { 
            get
            {
                return _msg;
            }

            set
            {
                _msg = value;
                if (PropertyChanged!=null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Message"));
                    CommandManager.InvalidateRequerySuggested();

                }
            }
        }


        public ViewMode()
        {
            cm1click = new DelegateCommand(cm1Click, Cancm1Click);
        }


        #region command1

        public ICommand cm1click { get; set; }
        public void cm1Click(object param)
        {
            MessageBox.Show("CM1 clicked!");
        }

        private bool Cancm1Click(object param)
        {
            return Message != "";
        }

        #endregion command1
    }
}

猜你喜欢

转载自blog.csdn.net/dxm809/article/details/107241873
WPF