内容说明:视频教程总结
代码平台:visual studio 2019
内容简介:使用wpf的MVVM框架(view-model -viewmodel)实现简单数据绑定及行为绑定,实现前后端代码的分离; 实例为两个数相加,并显示计算结果。
1.view---MainWindow.xaml
2.MainWindow.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace MVVMdemo
{
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
}
}
3.NotificationObject.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Windows;
namespace MVVMdemo
{
class NotificationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
4.viewmodel---MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MVVMdemo
{
class MainWindowViewModel:NotificationObject
{
//输入值1
private double input1;
public double Input1
{
get { return input1; }
set
{
input1 = value;
this.RaisePropertyChanged("Input1");
}
}
private double input2;
//输入值2
public double Input2
{
get { return input2; }
set
{
input2 = value;
this.RaisePropertyChanged("Input2");
}
}
//计算结果
private double result;
public double Result
{
get { return result; }
set
{
result = value;
this.RaisePropertyChanged("Result");
}
}
//
public DelegateCommand AddCommand { get; set; }
private void Add(object parameter)
{
//计算代码段
this.Result = this.Input1 + this.Input2;
}
public MainWindowViewModel()
{
this.AddCommand = new DelegateCommand();
this.AddCommand.ExecuteAction = new Action
5.DelegateCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace MVVMdemo
{
class DelegateCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return true;
//if (CanExecuteFunc == null)
//{
//}
//this.CanExecuteFunc(parameter);
}
public void Execute(object parameter)
{
if (ExecuteAction == null)
{
return;
}
this.ExecuteAction(parameter);
}
public Action



