WPF UI开发教程ICommand MVVM 实现

92 篇文章 9 订阅
92 篇文章 23 订阅

命令为视图提供了一种机制来更新 MVVM 架构中的模型。命令提供了一种在元素树中搜索命令处理程序的方法。ICommand 接口在 System.Windows.Input 命名空间内定义。它有两个方法和一个事件。

只有当 CanExecute 返回 true 时才会调用 Execute 方法。如果 CanExecute 方法返回 false,则绑定控件将自动禁用。

为了了解 CanExecute 值,请收听 CanExecuteChanged 事件,该事件可能因传递的参数而异。

使用代码

ICommand 的使用

ICommand接口一般用在MVVM架构中。在 Button 控件中,Command 属性绑定到“SearchCommand”。由于 SearchCommand只不过是一个 ICommand 实例,因此在加载窗口时,它将检查 CanExecute 返回值,如果返回 true,则它将启用按钮控件并且 Execute 方法已准备好使用,否则按钮控件将被禁用。

<Button Width= "100"  Height= "20"  Horizo​​ntalAlignment= "Center"  Grid.Row= "1"  Content= "Update"  Command= "{Binding Path=SearchCommand}" />  

在ViewModel中定义命令自动属性:

public ICommand SearchCommand { get; set; }

接下来在构造方法中初始化命令绑定方法

public ViewModel()
        {
            SearchCommand = new RelayCommand(Search);
        }

RelayCommand 是命令接口类实现:

 public class RelayCommand : ICommand
    {
        #region Private Members

        /// <summary>
        /// The _action to run
        /// </summary>
        private Action _action;

        #endregion

        #region Constructor

        /// <summary>
        /// Default constructor
        /// </summary>
        public RelayCommand(Action action)
        {
            _action = action;
        }

        #endregion

        #region Command Methods

        /// <summary>
        /// A relay command can always execute
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public bool CanExecute(object parameter)
        {
            return true;
        }

        /// <summary>
        /// Executes the commands Action
        /// </summary>
        /// <param name="parameter"></param>
        public void Execute(object parameter)
        {
            _action();
        }

        #endregion

        #region Public Events

        /// <summary>
        /// The event thats fired when the <see cref="CanExecute(object)"/> value has changed
        /// </summary>
        public event EventHandler CanExecuteChanged = (sender, e) => { };

        #endregion


    }

最后是命令绑定实现搜索方法

public void Search()
{
    Console.WriteLine("方法测试");
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值