Dav*_*son 8 wpf mvvm relaycommand delegatecommand
我刚学习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
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
这是我的命令:
public class SavePersonCommand: ICommand
{
#region ICommand Members
public bool CanExecute(object parameter)
{
return (parameter as PersonVM) != null;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
PersonVM person = parameter as PersonVM;
if(person != null)
//Actually Save the person...
}
#endregion
}
Run Code Online (Sandbox Code Playgroud)
我的方法有什么问题?
如果您不使用某些基本命令(框架的或您自己的自定义命令),您会发现自己一遍又一遍地编写相同的代码。例如:您不会CanExecuteChanged在自己的命令中引发事件。实施也是如此INotifyPropertyChanged。这就是为什么每个人都使用一个或另一个 MVVM 框架。
| 归档时间: |
|
| 查看次数: |
5454 次 |
| 最近记录: |