wpf自定義指令的資料網上很多,但基本上都是簡單提一下,想再深入一點總覺得差一點,例如今天我就碰到這樣的問題,自定義指令沒問題,網上一搜複制粘貼,搞定,但我要是想用個checkbox控制它生不生效怎麼弄呢?沒問題,現成的就有,引一個prism,示例程式裡就有,但一個指令引一個架構不太至于。
其實網上說的已經完成了一大半了,例如下面的:
class CustomCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object,bool> _canExecute;
public CustomCommand(Action<object> execute)
: this(execute, null)
{
}
public CustomCommand(Action<object> execute, Func<object, bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_canExecute = canExecute;
_execute = execute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
_execute(parameter);
}
}
使用:
public CustomCommand StartAndStopCommand { get; set; }
public MainViewModel()
{
StartAndStopCommand = new CustomCommand(p => { }, p =>
{
return true;
});
}
這裡的canexecute直接傳回true,指令一直生效。但要控制它的是否啟用這裡得改,改成這樣
public CustomCommand StartAndStopCommand { get; set; }
public bool canuse=false;
public MainViewModel()
{
StartAndStopCommand = new CustomCommand(p => { }, p =>
{
return canuse;
});
}
看着沒毛病,裡面傳回變量值,外面控制一下這個變量就可以實作了,但,真的是這樣嗎?運作之後發現并不是,不管外面怎麼改canuse的值,都控制不了指令的是否啟用。
原因很簡單,canexecute不知道它的enable改變了,仔細看代碼我們會發現指令的CanExecuteChanged我們隻是定義了,并沒用到,改成下面就可以了
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
一下是指令所有代碼:
class CustomCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object,bool> _canExecute;
public CustomCommand(Action<object> execute)
: this(execute, null)
{
}
public CustomCommand(Action<object> execute, Func<object, bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_canExecute = canExecute;
_execute = execute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
}
用法不變。