在您的 XAML 文件与您的 ViewModel 对话后,MVVMLight 在哪些其他方面有帮助

In what other areas is MVVMLight helpful after you have your XAML files talking with your ViewModels

据我了解,使用MVVM/MVVMLight的好处之一是可以将视图与模型分开,所以建议使用MVVMLight之类的库,这很清楚,实际上,我我正在使用 MVVMLight 来帮助实现将多页放在一起的机制,但我不完全理解的是,一旦你的页面(ViewModels 和 XAML 文件)与每个页面对话,MVVMLight 的其他部分是有用的其他.

例如,以下两个选项的工作方式相同,除了在选项 2 中我使用 MVVMLight 但我不完全理解的是我通过 MVVMLight 获得了什么。

我使用选项 2 而不是选项 1 有什么好处?

谁能给我几个例子,说明在 XAML 文件与 ViewModel 对话后,MVVMLight 如何提供帮助?

选项 1

XAML

<Button Content="Button"  Command="{Binding FindPdfFileCommand}"/> 

视图模型.cs

namespace Tool.ViewModel
{
    public class FindrViewModel : ViewModelBase
    { 
        public ICommand FindPdfFileCommand{get;private set;}
        public FindrViewModel(){ FindPdfFileCommand = new RelayCommand(() => FindPdfFile_Click());}

        private void FindPdfFile_Click()
        {
            Console.WriteLine("Button clicked");
        }
    }
}    

选项 2

XAML

    xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform"
    xmlns:Custom="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

    <Button x:Name="button" Content="Button">
        <Custom:Interaction.Triggers>
            <Custom:EventTrigger EventName="Click">
                <GalaSoft_MvvmLight_Command:EventToCommand x:Name="ClickMeEvent" Command="{Binding FindPdfFileCommand, Mode=OneWay}" />
            </Custom:EventTrigger>
        </Custom:Interaction.Triggers>
    </Button>

视图模型.cs

namespace Tool.ViewModel
{
    public class FindrViewModel : ViewModelBase
    { 
        public ICommand FindPdfFileCommand{get;private set;}
        public FindrViewModel(){ FindPdfFileCommand = new RelayCommand(() => FindPdfFile_Click());}

        private void FindPdfFile_Click()
        {
            Console.WriteLine("Button clicked");
        }
    }
}

RelayCommand(以及任何其他 ICommand 实现)在 Execute 操作之上添加了另一个关键功能 - 即 CanExecute 属性。

这允许您根据 ViewModel 对象的其他状态来控制何时可以执行命令。任何绑定的按钮(或其他带有命令 属性 这样的菜单项的控件)将在命令无法执行时自动禁用。 ViewModel 现在可以间接控制用户界面,无需直接了解命令的使用方式。

As I understand it, one of the benefits of using MVVM/MVVMLight is to separate the views from the models ...

这就是模式本身的目的。 MVVM 只是一种设计模式。如果你愿意,你可以自己实现它而无需使用任何第三方库,例如 MvvmLightPrism

使用库的主要好处是它为您提供了开箱即用的开发 MVVM 应用程序所需的大部分内容。例如,这包括一个基础 class,它引发实现 INotifyPropertyChanged 接口并引发更改通知和 ICommand 接口的实现。

在您的示例中,您使用的是 ViewModelBaseRelayCommand class 等。如果您不使用 MvvmLight,则必须自己实施这些。

EventToCommand 在这种情况下并不是很有用。主要用于当你想将事件的EventArgs作为命令参数传递给命令时:http://blog.galasoft.ch/posts/2014/01/using-the-eventargsconverter-in-mvvm-light-and-why-is-there-no-eventtocommand-in-the-windows-8-1-version/.

您不妨直接在此处绑定到命令 属性:

Command="{Binding FindPdfFileCommand}"/> 

但是您仍在视图模型中使用 MvvmLight 类型。