参考JusterZhu视频和文档,ppt文档基本全抄
日常开发中必不可少会用到命令,比如button自带了Command和CommandParameter属性。细心的小伙可能会发现并不是所有的控件都自带这样的属性,那么如何让“万物皆可Command”呢?
通常使用System.Windows.Interactivity.dll提供的Interaction对象,它的本质是附加属性可以附加到wpf所有的控件之上,因为所有wpf控件的基类都是DependencyObject的。
避免版本问题,推荐使用Microsoft.Xaml.Behaviors.Wpf 该组件支持.net5
https://github.com/Microsoft/XamlBehaviorsWpf
如何使用Interactivity 对象?
internal class MainViewModel
{
public ICommand TestCommand { get; set; }
public MainViewModel()
{
TestCommand = new RelayCommand(TestCallBack);
}
private void TestCallBack()
{
Application.Current.Dispatcher.Invoke(() =>
{
MessageBox.Show("hello world.");
});
}
}
public class RelayCommand : ICommand
{
#region 字段
readonly Func _canExecute;
readonly Action _execute;
#endregion
#region 构造函数
public RelayCommand(Action execute) : this(execute, null)
{
}
public RelayCommand(Action execute, Func canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand的成员
public event EventHandler CanExecuteChanged
{
add
{
if (_canExecute != null)
CommandManager.RequerySuggested += value;
}
remove
{
if (_canExecute != null)
CommandManager.RequerySuggested -= value;
}
}
[DebuggerStepThrough]
public Boolean CanExecute(Object parameter)
{
return _canExecute == null ? true : _canExecute();
}
public void Execute(Object parameter)
{
_execute();
}
#endregion
}
///
/// A command whose sole purpose is to
/// relay its functionality to other
/// objects by invoking delegates. The
/// default return value for the CanExecute
/// method is 'true'.
///
public class RelayCommand : ICommand
{
#region Constructors
public RelayCommand(Action execute)
: this(execute, null)
{
}
///
/// Creates a new command.
///
/// The execution logic.
/// The execution status logic.
public RelayCommand(Action execute, Predicate canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute((T)parameter);
}
public event EventHandler CanExecuteChanged
{
add
{
if (_canExecute != null)
CommandManager.RequerySuggested += value;
}
remove
{
if (_canExecute != null)
CommandManager.RequerySuggested -= value;
}
}
public void Execute(object parameter)
{
_execute((T)parameter);
}
#endregion // ICommand Members
#region Fields
readonly Action _execute = null;
readonly Predicate _canExecute = null;
#endregion // Fields
}