我刚开始在应用程序中使用MVVM命令.我找到了很多例子,并在我的代码中尝试了两种方式.一些示例在xaml中具有命令绑定,如下所示:
<CommandBinding Command="local:MainWindow.OpenRecentFile"
Executed="{Binding OpenRecentFile_Executed}" />
...
<MenuItem Header="{x:Static culture:TextResource.RecentFilesMenuItem}"
Command="local:MainWindow.RecentFilesCommand" >
Run Code Online (Sandbox Code Playgroud)
使用OpenRecentFile_Executed是ViewModel中的方法和静态ICommand,如下所示:
public static readonly ICommand OpenRecentFile =
new RoutedCommand("Open Recent", typeof(MainWindow));
Run Code Online (Sandbox Code Playgroud)
我还看到了ViewModel上有一个属性ICommand的属性,它在视图中被绑定到这样:
<MenuItem Header="Close Current File"
Command="{Binding CloseCurrentFileCommand}"
CommandParameter="{TemplateBinding DataContext}"/>
Run Code Online (Sandbox Code Playgroud)
并在ViewModel中:
private ICommand closeCurrentFileCommand;
public ICommand CloseCurrentFileCommand
{
get
{
if (closeCurrentFileCommand == null)
{
closeCurrentFileCommand =
new RelayCommand(param => this.CloseCurrentCedarFile(param));
}
return closeCurrentFileCommand;
}
}
Run Code Online (Sandbox Code Playgroud)
每种方法有哪些好处/缺点?
这取决于你的设计.如果你想采用快速方法 - 一个带有后端代码的Window,那么在XAML中声明命令可能会节省你一些时间并减少长期工作量.
如果您要使用MVVM应用程序,那么我强烈建议绑定到ICommand,因为命令通常是操作数据的方式(打开/保存/编辑),这应该在ViewModel中定义.可能更多的努力取决于功能,但如果你正在做一个更大的应用程序,MVVM是一个很好的方法.
最后两者都会起作用,但这是你的设计和方法.
我认为这些之间的主要区别在于第一版的路由特性.路由方面可以使命令在某些情况下更强大,但它也可能导致更多的痛苦.如果你试图让命令执行,但是目标ui元素没有焦点,那么痛苦就会发挥作用.
基于属性的ICommand实现将始终有效,因为命令调用和命令传递之间没有"路由"步骤.
除非我的场景需要路由提供的功能,否则我倾向于使用大多数基于属性的命令.
| 归档时间: |
|
| 查看次数: |
11665 次 |
| 最近记录: |