如何用WPF实现一个最简单的Mvvm示例

 时间:2026-02-16 12:12:59

1、创建一个 ViewModelBase

public abstract class ViewModelBase : INotifyPropertyChanged{

    //属性改变事件

    public event PropertyChangedEventHandler PropertyChanged;

   

    //当属性改变的时候,调用该方法来发起一个消息,通知View中绑定了propertyName的元素做出调整

    public void RaisePropertyChanged(string propertyName)

    {

        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)

        {

            handler(this, new PropertyChangedEventArgs(propertyName));

        }

    }

}

2、创建一个DelegateCommand

public class DelegateCommand : ICommand{

    readonly Action<object> _execute;

    readonly Predicate<object> _canExecute;

  

    public DelegateCommand(Action<object> execute)

        : this(execute, null)

    {

    }

    public DelegateCommand(Action<object> execute, Predicate<object> canExecute)

    {

        if (execute == null)

            throw new ArgumentNullException("execute");

        _execute = execute;

        _canExecute = canExecute;

    }

    public void Execute(object parameter)

    {

        _execute(parameter);

    }

    public bool CanExecute(object parameter)

    {

        return _canExecute == null ? true : _canExecute(parameter);

    }

    public event EventHandler CanExecuteChanged

    {

        add { CommandManager.RequerySuggested += value; }

        remove { CommandManager.RequerySuggested -= value; }

    }

}

  • IIS 7.0安装流程
  • Windows系统怎么设置屏幕分辨率
  • win7电脑系统如何设置文件默认打开程序?
  • 电脑登录密码策略更改
  • 如何使用ckplayer播放网页
  • 热门搜索
    谁有快猫可以发一下么 拉直头发几天可以洗 烟台山景区 可以赚钱的软件 乌兰察布旅游 淘宝的会员名怎么改 鸡蛋和牛奶可以一起吃吗 拉肚子拉血怎么回事 结婚证不见了怎么办 北京现代音乐学院怎么样