简单实现Wpf的MVVM模式

MVVM旨在数据驱动,通过绑定的模式实现前后端交互。最重要的就是属性更改时的通知功能以及命令(Command)的绑定。

一、定义通知类(BindableBase)

Prism框架有个BindableBase的基类,可以实现属性更改后通知前端。这里实现一个类似的BindableBase类。
首先继承INotifyPropertyChanged接口,并对事件PropertyChanged调用即可。

public class BindableBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisedPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyName));
    }
}

二、定义Command类(DelegateCommand)

类似Prism框架里的DelegateCommand,简单实现其功能,但和Prism差很多,Prism扩展功能要多很多。
DelegateCommand继承ICommand接口,并实现接口的CanExecute、Execute方法;

public class DelegateCommand<T> : ICommand
    {
        public event EventHandler CanExecuteChanged;

        public DelegateCommand(Action<T> execute, Func<T, bool> canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter)
        {
            if(_canExecute == null)
            {
                return true;
            }
            return _canExecute((T)parameter);
        }

        public void Execute(object parameter)
        {
            _execute((T)parameter);
        }
        private Action<T> _execute;
        private Func<T, bool> _canExecute;
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值