我对命令模式感到困惑.关于这些命令有很多不同的解释.我认为下面的代码是委托命令,但在阅读了关于relaycommand后,我有点怀疑.
relay命令,delegatecommand和routedcommand之间的区别是什么.是否可以在与我发布的代码相关的示例中显示?
class FindProductCommand : ICommand
{
ProductViewModel _avm;
public FindProductCommand(ProductViewModel avm)
{
_avm = avm;
}
public bool CanExecute(object parameter)
{
return _avm.CanFindProduct();
}
public void Execute(object parameter)
{
_avm.FindProduct();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
Run Code Online (Sandbox Code Playgroud) 我刚学习WPF中的MVVM,我对WPF和MVVM都是全新的(我理解它是如何工作的,但从未使用它......)
我在网上找到的每一篇教程/文章都使用了RelayCommand或DelegateCommand.
在我的观察中,这些模式迫使VM违反SRP原则,因为它将把命令逻辑保存在其中.
为什么不使用ICommand接口的自定义实现?像这样:
想象一下,您正在显示一个人并将其保存到数据库中:
我的Xaml就是这样的:
<StackPanel>
<TextBlock Width="248" Height="24" Text="The name is:: " />
<TextBlock Width="248" Height="24" Text="{Binding Name}">
</TextBlock>
<TextBox HorizontalAlignment="Left" Name="textBox1" Width="120" Height="23"
VerticalAlignment="Top" Text="{Binding Name}"
/>
<Button Name="Salvar" VerticalAlignment="Bottom"
Command="{Binding SavePerson}"
CommandParameter="{Binding}">Save</Button>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)
这是我的VM:
public class PersonVM: INotifyPropertyChanged
{
private string nameValue;
public string Name
{
get{
return nameValue;
}
set
{
if (value != this.nameValue)
{
this.nameValue= value;
NotifyPropertyChanged("Name");
}
}
}
public ICommand SavePerson{ get { return new SavePersonCommand(); } }
#region INotifyPropertyChanged Members …Run Code Online (Sandbox Code Playgroud)