gpt4 book ai didi

mvvm - 为什么 ViewModel 不在 MVVM 中实现 ICommand

转载 作者:行者123 更新时间:2023-12-02 08:42:25 26 4
gpt4 key购买 nike

我正在尝试了解 WPF 应用程序的 MVVM

在下面的示例中,我们使用了一个继承自 ICommand 的委托(delegate),然后在我们的 ViewModel 中,我们实例化该委托(delegate)并提供适当的实现

我的问题是为什么我们不能让 ViewModel 实现 ICommand?

View 模型:

public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
InitializeViewModel();
}

protected void InitializeViewModel()
{
DelegateCommand MyCommand = new DelegateCommand<SomeClass>(
SomeCommand_Execute, SomeCommand_CanExecute);
}

void SomeCommand_Execute(SomeClass arg)
{
// Implementation
}

bool SomeCommand_CanExecute(SomeClass arg)
{
// Implementation
}
}

委托(delegate)命令:

public class DelegateCommand<T> : ICommand
{
public DelegateCommand(Action<T> execute) : this(execute, null) { }

public DelegateCommand(Action<T> execute, Predicate<T> canExecute) : this(execute, canExecute, "") { }

public DelegateCommand(Action<T> execute, Predicate<T> canExecute, string label)
{
_Execute = execute;
_CanExecute = canExecute;
}
.
.
.
}

最佳答案

原因是您的 View 和命令数量之间存在一对多关系。

您通常会为每个 View 创建一个 ViewModel。但是您可能希望为单个 View 设置多个命令。如果您要将 ViewModel 用作命令,则必须有多个 ViewModel 实例。

典型的实现是您的 ViewModel 将包含您的 View 所需的所有命令的实例。

关于mvvm - 为什么 ViewModel 不在 MVVM 中实现 ICommand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15392845/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com