WPF与MVVM的实现(四)命令绑定

来源:互联网 发布:网络悲伤情歌 编辑:程序博客网 时间:2024/06/08 19:49

    接触WPF已经有两年,大大小小开发过几个项目,但从来没有系统的去学习过。几次开发项目时都觉得十分的恼火,太多的事件稍微考虑不到位就会带来麻烦,为此特地系统的看了一本《C#高级编程》第10版,了解到MVVM框架,看了之后十分欢喜,本篇记录研究MVVM过程。

0001 ICommand接口的实现


public class RelayCommand : ICommand{#region Fields readonly Action<object> _execute;readonly Predicate<object> _canExecute; #endregion // Fields #region Constructors /// <summary>/// Creates a new command that can always execute./// </summary>/// <param name="execute">The execution logic.</param>public RelayCommand(Action<object> execute): this(execute, null){} /// <summary>/// Creates a new command./// </summary>/// <param name="execute">The execution logic.</param>/// <param name="canExecute">The execution status logic.</param>public RelayCommand(Action<object> execute, Predicate<object> canExecute){if (execute == null)throw new ArgumentNullException("execute"); _execute = execute;_canExecute = canExecute;} #endregion // Constructors #region ICommand Members [DebuggerStepThrough]public bool CanExecute(object parameters){return _canExecute == null ? true : _canExecute(parameters);} public event EventHandler CanExecuteChanged{add { CommandManager.RequerySuggested += value; }remove { CommandManager.RequerySuggested -= value; }} public void Execute(object parameters){_execute(parameters);} #endregion // ICommand Members }


0010 不带参数的命令绑定

前台:

<Button x:Name="button" Content="添加" Command="{Binding AddTimeCommand}" HorizontalAlignment="Left" Margin="288,158,0,0" VerticalAlignment="Top" Width="89" Height="36"> </Button>


后台:

RelayCommand _addTimeCommand = null;public ICommand AddTimeCommand{get{if (null == _addTimeCommand){_addTimeCommand = new RelayCommand((p) => OnAddTime(), (p) => CanAddTime());}return _addTimeCommand;}}bool CanAddTime(){return true;}void OnAddTime(){MyDateTime.Add(DateTime.Now.ToString());}



0011 带参数的命令绑定

前台:

<Button x:Name="button2" Content="修改" Command="{Binding ChangeTimeCommand}" CommandParameter="button2" HorizontalAlignment="Left" Margin="382,199,0,0" VerticalAlignment="Top" Width="89" Height="36"></Button>


后台:

public RelayCommand ChangeTimeCommand{get{return new RelayCommand(OnChangeTime, CanChangeTime);}}bool CanChangeTime(object parameter){return true;}void OnChangeTime(object parameter){if (MyDateTime.Count > 0){MyDateTime.RemoveAt(0);MyDateTime.Insert(0, DateTime.Now.ToString());}}


 

原创粉丝点击