Ejemplo n.º 1
0
        protected virtual void OnExecuting(CommandExecutingEventArgs e)
        {
            var executing = this.Executing;

            if (executing != null)
            {
                executing(this, e);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 执行命令。
        /// </summary>
        /// <param name="parameter">执行命令的参数。</param>
        /// <returns>返回执行的返回结果。</returns>
        /// <remarks>
        ///		<para>本方法的实现中首先调用<see cref="CanExecute"/>方法,以确保阻止非法的调用。</para>
        /// </remarks>
        protected virtual object Execute(object parameter)
        {
            //在执行之前首先判断是否可以执行
            if (!this.CanExecute(parameter))
            {
                return(null);
            }

            //创建事件参数对象
            var executingArgs = new CommandExecutingEventArgs(parameter, null);

            //激发“Executing”事件
            this.OnExecuting(executingArgs);

            //如果事件处理程序要取消后续操作,则返回退出
            if (executingArgs.Cancel)
            {
                return(executingArgs.Result);
            }

            object result = executingArgs.Result;
            CommandExecutedEventArgs executedArgs;

            try
            {
                //执行具体的工作
                result = this.OnExecute(parameter);
            }
            catch (Exception ex)
            {
                //创建事件参数对象
                executedArgs = new CommandExecutedEventArgs(parameter, ex);

                //激发“Executed”事件
                this.OnExecuted(executedArgs);

                if (!executedArgs.ExceptionHandled)
                {
                    throw;
                }

                return(executedArgs.Result);
            }

            //创建事件参数对象
            executedArgs = new CommandExecutedEventArgs(parameter, result);

            //激发“Executed”事件
            this.OnExecuted(executedArgs);

            //返回执行成功的结果
            return(executedArgs.Result);
        }