2016年2月29日月曜日

RelayCommand.cs

【参考】http://d.hatena.ne.jp/kaorun/20141202/1417532472
 ICommandの簡単実装
--------------------------
 ViewModel内で宣言
・宣言    
public ICommand Event_name { get; set; }
・コンストラクタで初期化
Event_name = new RelayCommand( Process_name );
・実処理は別に作成(簡単な処理ならlambdaで)       
public void Process_name(){
   処理内容;
 (例:インクリメント、メッセージボックス表示)
}
--------------------------
Common内で定義
【RelayCommand.cs】
using System;
using System.Windows.Input;
namespace Project.Common
{
    public class RelayCommand : ICommand
    {
        private readonly Action _execute;
        private readonly Func<bool> _canExecute;

        public event EventHandler CanExecuteChanged;

        public RelayCommand(Action execute) : this(execute, null)
        {
        }
        public RelayCommand(Action execute, Func<bool> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute();
        }
        public void Execute(object parameter)
        {
            _execute();
        }
        public void RaiseCanExecuteChanged()
        {
            var handler = CanExecuteChanged;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

    }
}

0 件のコメント:

コメントを投稿