##为什么要使用Command?
主要是在MVVM中 实现业务与UI分离,所以不想在Click事件里写东西,换成了一个Command
For example:Click 方式
一个Button,如下
<WrapPanel>
<Button Content="Button" Click="Button_Click" />
</WrapPanel>
private void Button_Click(object sender, RoutedEventArgs e)
{
MessageBox.Show("Hello World");
}
Command 方式
public partial class Window3 : Window
{
public Window3()
{
InitializeComponent();
btn.Command = new MyCommand();
}
//private void Button_Click(object sender, RoutedEventArgs e)
//{
// MessageBox.Show("Hello World");
//}
}
public class MyCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
MessageBox.Show("Hello World");
}
}
##ICommand最佳使用方法
public class RelayCommand:ICommand
{
private Predicate<object> _canExecute;
private Action<object> _execute;
public RelayCommand(Predicate<object> canExecute, Action<object> execute)
{
this._canExecute = canExecute;
this._execute = execute;
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
}
使用:
public class MyViewModel
{
private ICommand _doSomething;
public ICommand DoSomethingCommand
{
get
{
if (_doSomething == null)
{
_doSomething = new RelayCommand(
p => this.CanDoSomething,
p => this.DoSomeImportantMethod());
}
return _doSomething;
}
}
}
其中,Predicate:MSDN
表示一种方法,该方法定义一组条件并确定指定对象是否符合这些条件。
using System;
using System.Drawing;
public class Example
{
public static void Main()
{
// Create an array of Point structures.
Point[] points = { new Point(100, 200),
new Point(150, 250), new Point(250, 375),
new Point(275, 395), new Point(295, 450) };
// Define the Predicate<T> delegate.
Predicate<Point> predicate = FindPoints;
// Find the first Point structure for which X times Y
// is greater than 100000.
Point first = Array.Find(points, predicate);
// Display the first structure found.
Console.WriteLine("Found: X = {0}, Y = {1}", first.X, first.Y);
}
private static bool FindPoints(Point obj)
{
return obj.X * obj.Y > 100000;
}
}
// The example displays the following output:
// Found: X = 275, Y = 395
Action:MSDN
封装一个方法,该方法只有一个参数且不返回值。