1.先写一个BaseCommand类,继承ICommand,点击实现接口。(1个事件,2个方法)
public class BaseCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
throw new NotImplementedException();
}
public void Execute(object parameter)
{
throw new NotImplementedException();
}
}
最终代码
public class BaseCommand : ICommand
{
//一个事件2个方法
/// <summary>
/// 一个参数,不返回方法
/// </summary>
public Action<object> ExecuteAction { get; set; }
/// <summary>
/// 一个参数,返回方法
/// </summary>
public Func<object,bool> CanExecuteAction { get; set; }
/// <summary>
/// 当能不能做发生变化时会触发的事件(必须要实现)
/// </summary>
public event EventHandler CanExecuteChanged;
/// <summary>
/// 能做吗(必须要实现)
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
if (CanExecuteAction != null)
return CanExecuteAction(parameter);
return false;
}
/// <summary>
/// 做什么(必须要实现)
/// </summary>
/// <param name="parameter"></param>
public void Execute(object parameter)
{
ExecuteAction?.Invoke(parameter);
}
}
2.创建ViewModel类
class ViewModel
{
//先实例化这个命令(这是属于ViewModel的命令,等下要被送到View中去)
public BaseCommand MyCommand { get; set; }
public ViewModel()
{
//在ViewModel的构造函数中,完成对命令的设置
MyCommand = new BaseCommand();
MyCommand.ExecuteAction = new Action<object>(this.DoSomething);
MyCommand.CanExecuteAction = new Func<object, bool>(this.CanDoSomething);
}
public void DoSomething(object param)
{
MessageBox.Show("123"+param);
}
public bool CanDoSomething(object param)
{
return true; //判断能否做这个事情,大部分时候返回true就行了
}
}
3.View界面中指定
4.前端界面显示,CommandParameter是命令的参数
<Grid>
<StackPanel Height="295" HorizontalAlignment="Left" Margin="10,10,0,0" Tag="7777" Name="stackPanel1" VerticalAlignment="Top" Width="427">
<Button Name="A" Content="aa" Command="{Binding MyCommand}" CommandParameter="{Binding ElementName=stackPanel1,Path=Tag}" Width="60"/>
</StackPanel>
</Grid>
5.效果