// 摘要:
// Defines a command.
public interface ICommand
{
//
// 摘要:
// Occurs when changes occur that affect whether or not the command should execute.
event EventHandler CanExecuteChanged;
//
// 摘要:
// Defines the method that determines whether the command can execute in its current
// state.
//
// 参数:
// parameter:
// Data used by the command. If the command does not require data to be passed,
// this object can be set to null.
//
// 返回结果:
// true if this command can be executed; otherwise, false.
bool CanExecute(object parameter);
//
// 摘要:
// Defines the method to be called when the command is invoked.
//
// 参数:
// parameter:
// Data used by the command. If the command does not require data to be passed,
// this object can be set to null.
void Execute(object parameter);
上面这个是ICommand包含的类容,通过一个小例子来说明她的使用方法,
首先在Window里添加一个Button和一个Textbox,给Button绑定一个命令,给Text box绑定一个int数字,当int 数字小于0是Button不可用。
首先创建命令:
public class OK_Command : ICommand
{
private ViewModel _vm = null;
public OK_Command(ViewModel vm)
{
_vm = vm;
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
if(CanExecuteChanged!=null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
public bool CanExecute(object parameter)
{
if (_vm.Num < 0)
return false;
return true;
}
public void Execute(object parameter)
{
MessageBox.Show("OK");
}
}
创建View Model:
public class ViewModel : INotifyPropertyChanged
{
private int _num = 0;
public int Num
{
get
{
return _num;
}
set
{
_num = value;
RaisePropertyChanged(nameof(Num));
RaisePropertyChanged((nameof(OK_Command)));
}
}
private OK_Command _okCommand = null;
public OK_Command OK_Command
{
get
{
if(_okCommand ==null)
{
_okCommand = new OK_Command(this);
}
_okCommand.RaiseCanExecuteChanged();
return _okCommand;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string name)
{
if(PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
在Window里添加Button和TextBox 并设置绑定路径
<Window x:Class="ICommandDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ICommandDemo"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Button x:Name="button" Command="{Binding Path=OK_Command}" Content="Button" HorizontalAlignment="Left" Margin="334,268,0,0" VerticalAlignment="Top" Width="75"/>
<TextBox x:Name="textBox" HorizontalAlignment="Left" Height="23" Margin="288,176,0,0" TextWrapping="Wrap" Text="{Binding Path= Num,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
</Grid>
</Window>
最后在Window启动设置Data Context
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModel();
}
}