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

2025-03-30 14:41:21
推荐回答(1个)
回答1:

基类NotificationObject
class NotificationObject:INotifyPropertyChanged //ViewModel的基类,作用是通知ViewModels的变化
    {
       public event PropertyChangedEventHandler PropertyChanged;
       public void RaisePropertyChanged(string propertyName)
        {
           if (this.PropertyChanged!=null)
            {
                this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
简单基类DelegateCommand 
class DelegateCommand:ICommand
{
    public boolCanExecute(object parameter)
    {
        if (this.CanExecuteFunc==null)
        {
            return true;
        }
       return this.CanExecuteFunc(parameter);
    }
    public event EventHandler CanExecuteChanged;
    public void Execute(object parameter)
    {
        if (this.ExecuteAction==null)
        {
            return;
        }
        this.ExecuteAction(parameter);
    }
    public Action
ExecuteAction { get; set; }
    public Func CanExecuteFunc { get; set; }  
}
ViewModel
class MainWindowViewModel : NotificationObject
    {
        //以下3个属性是用来做数据传输的数据属性  
       private double input1;
       public double Input1
        {
           get { returninput1; }
           set
            {
                input1 = value;
                this.RaisePropertyChanged("Input1");
            }
        }
       private double input2;
       public double Input2
        {
           get { returninput2; }
           set
            {
                input2 = value;
                this.RaisePropertyChanged("Input2");
            }
        }
       private double result;
       public double Result
        {
           get { returnresult; }
           set
            {
                result = value;
                this.RaisePropertyChanged("Result");
            }
        }
        //下面这个属性就是用来做操作传输的命令属性      
       public DelegateCommand AddCommand { get; set; }
       private void Add(objectparameter)
        {
           string s = System.IO.Directory.GetCurrentDirectory();
           string s1 = Environment.CurrentDirectory;
           MessageBox.Show(s+"\r\n"+s1);
        }       
 
        //在构造函数中关联命令属性 
       public MainWindowViewModel()
        {            
this.AddCommand = new DelegateCommand(new Action(Add));
        }
//命令属性也可以用以下方式
public DelegateCommand command1 { get { return new DelegateCommand(new Action(() => MessageBox.Show("a")));
} }
 
    }
View
在view里,可以在后台绑定如
this.DataContext = new MainWindowViewModel();
也可以在XAML里绑定
 
xmlns:viewmodel="clr-namespace:SimpleMvvmDemo.ViewModels"