1.首先定义NotificationObject类。目的是绑定数据属性。
using System.ComponentModel;
namespace WpfFirst
{
class NotificationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
2.定义DelegateCommand类。目的是绑定命令属性。
using System;
using System.Collections.Generic;
using System.Windows.Input;
namespace WpfFirst
{
class DelegateCommand : ICommand
{
//A method prototype without return value.
public Action<object> ExecuteCommand = null;
//A method prototype return a bool type.
public Func<object, bool> CanExecuteCommand = null;
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
if (CanExecuteCommand != null)
{
return this.CanExecuteCommand(parameter);
}
else
{
return true;
}
}
public void Execute(object parameter)
{
if (this.ExecuteCommand != null) this.ExecuteCommand(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}
3.开始定义Model类。
using System.ComponentModel;
using System.Windows.Input;
namespace WpfFirst
{
class Model : NotificationObject
{
private string _wpf = "WPF";
public string WPF
{
get { return _wpf; }
set
{
_wpf = value;
this.RaisePropertyChanged("WPF");
}
}
public void Copy(object obj)
{
this.WPF += " WPF";
}
}
}
4.定义ViewModel类。
using System;
namespace WpfFirst
{
class ViewModel
{
public DelegateCommand CopyCmd { get; set; }
public Model model { get; set; }
public ViewModel()
{
this.model = new Model();
this.CopyCmd = new DelegateCommand();
this.CopyCmd.ExecuteCommand = new Action<object>(this.model.Copy);
}
}
}
5.定义View.
<Window x:Class="WpfFirst.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<StackPanel VerticalAlignment="Center" >
<TextBlock Text="{Binding model.WPF}" Height="208" TextWrapping="WrapWithOverflow"></TextBlock>
<Button Command="{Binding CopyCmd}" Height="93" Width="232">Copy</Button>
</StackPanel>
</Grid>
</Window>
MainWindow.xaml.cs代码
using System.Windows;
namespace WpfFirst
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new ViewModel();
}
}
}