C# 在WPF MVVM中从Deleagte命令调用的函数中传递参数的对象类型
为什么以下函数在WPF MVVM中采用对象类型的参数C# 在WPF MVVM中从Deleagte命令调用的函数中传递参数的对象类型,c#,wpf,mvvm,delegatecommand,C#,Wpf,Mvvm,Delegatecommand,为什么以下函数在WPF MVVM中采用对象类型的参数 public ViewModel() { SaveCommand2 = new DelegateCommand(SaveCommand_Execute); } bool SaveCommand_CanExecute(object arg) { return Model.Name != string.Empty; } 默认情况下,我们不会将任何内容作为参数传递到函数中,因为会将NULL传递到函数中 若我们不想传
public ViewModel()
{
SaveCommand2 = new DelegateCommand(SaveCommand_Execute);
}
bool SaveCommand_CanExecute(object arg)
{
return Model.Name != string.Empty;
}
默认情况下,我们不会将任何内容作为参数传递到函数中,因为会将NULL传递到函数中
若我们不想传递任何东西,最好从函数中删除参数。但这是不允许的。
为什么?DelegateCommand是用于创建命令的“通用”实现。WPF命令有一个可选选项,用于在执行时向命令提供数据。这就是为什么
DelegateCommand
有一个类型为object
的参数,如果使用命令参数绑定,则该参数通过该参数传递。DelegateCommand是创建命令的“通用”实现。WPF命令有一个可选选项,用于在执行时向命令提供数据。这就是为什么DelegateCommand
有一个类型为object
的参数,如果使用命令参数绑定,则该参数将通过该参数传递。我认为您可以创建委托
命令的自定义实现来解决此问题。您可以查看以获取更多信息 我认为您可以创建delegate
命令的自定义实现来解决这个问题。您可以查看以获取更多信息 试试这个
public ViewModel()
{
SaveCommand2 = new DelegateCommand(new Action(() =>
{
//Your action stuff.
}), SaveCommand_CanExecute);
}
bool SaveCommand_CanExecute()
{
return Model.Name != string.Empty;
}
试试这个
public ViewModel()
{
SaveCommand2 = new DelegateCommand(new Action(() =>
{
//Your action stuff.
}), SaveCommand_CanExecute);
}
bool SaveCommand_CanExecute()
{
return Model.Name != string.Empty;
}
如果实现自己的DelegateCommand,则可以使用构造函数接收无参数操作,如以下代码所示:
public DelegateCommand(Action<object> execute, Func<object, bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute", "execute cannot be null");
if (canExecute == null)
throw new ArgumentNullException("canExecute", "canExecute cannot be null");
_execute = execute;
_canExecute = canExecute;
}
public DelegateCommand(Action<object> execute)
: this(execute, (o) => true)
{
}
public DelegateCommand(Action execute)
: this((o) => execute())
{
}
其中方法是无参数的如果您实现了自己的DelegateCommand,则可以让构造函数接收无参数操作,如以下代码所示:
public DelegateCommand(Action<object> execute, Func<object, bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute", "execute cannot be null");
if (canExecute == null)
throw new ArgumentNullException("canExecute", "canExecute cannot be null");
_execute = execute;
_canExecute = canExecute;
}
public DelegateCommand(Action<object> execute)
: this(execute, (o) => true)
{
}
public DelegateCommand(Action execute)
: this((o) => execute())
{
}
其中方法是无参数的