public class DelegateCommands:ICommand
{
public bool CanExecute(object parameter)
{
if (CanExecuteHander == null)
return true;
return CanExecuteHander(parameter);
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (ExecuteHander == null)
return;
ExecuteHander(parameter);
}
public Func<object, bool> CanExecuteHander;
public Action<object> ExecuteHander;
}
/// <summary>
/// 通知属性
/// </summary>
public class NotifyPropertyChanged:INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RasePropertyChange(string propertyName)
{
if (PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class AddViewModel:NotifyPropertyChanged
{
private int input1;
public int Input1
{
get { return this.input1; }
set
{
this.input1 = value;
this.RasePropertyChange("Input1");
}
}
private int input2;
public int Input2
{
get { return this.input2; }
set
{
this.input2 = value;
this.RasePropertyChange("Input2");
}
}
private int result;
public int Result
{
get { return this.result; }
set
{
this.result = value;
this.RasePropertyChange("Result");
}
}
public DelegateCommands Add { get; set; }
public void AddResult(object parameter)
{
this.Result = this.Input1 + this.Input2;
}
public AddViewModel()
{
this.Add = new DelegateCommands();
Add.ExecuteHander += new Action<object>(AddResult);
}
}
<StackPanel Orientation="Horizontal" Margin="20">
<TextBox Text="{Binding Input1}" ></TextBox>
<TextBox Text="{Binding Input2}"></TextBox>
<TextBox Text="{Binding Result}"></TextBox>
<Button Command="{Binding Add}">加</Button>
</StackPanel>
public MainWindow()
{
InitializeComponent();
this.DataContext = new AddViewModel();
}
注:在xaml文件中绑定数据以及命令的数据源,WPF默认情况下会使用冒泡的方式找DataContent的对象