何时为WPF/MVVM使用事件和命令?

Ayd*_*yed 4 c# wpf events command mvvm

我正在练习如何使用MVVM模式编写WPF应用程序.到目前为止,我还没有在我的代码中使用命令.在我的Viewmodel中,我实现INotifyPropertyChanged并使用(事件PropertyChangedEventHandler PropertyChanged)来触发事件.为什么我觉得我仍然错过了一些关于如何使用命令的WPF概念?

什么时候使用命令?

Fed*_*gui 11

WPF中的命令用于抽象用户触发的操作(例如单击Button或按键.

这是一个基本的例子:

假设您想在用户单击"搜索"按钮时搜索数据库中的员工,或者在聚焦搜索框时点击回车键.

您可以像这样定义ViewModel:

public class MyViewModel: ViewModelBase
{
    public string SearchText {get;set;} //NotifyPropertyChanged, etc.

    public Command SearchCommand {get;set;}

    public MyViewModel()
    {
        //Instantiate command
        SearchCommand = new DelegateCommand(OnSearch);
    }

    private void OnSearch()
    {
        //... Execute search based on SearchText
    }
}
Run Code Online (Sandbox Code Playgroud)

而你的观点:

<StackPanel>
    <TextBox Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}">
        <TextBox.InputBindings>
            <KeyBinding Key="Enter" Command="{Binding SearchCommand}"/>
        </TextBox.InputBindings>
    </TextBox>
    <Button Content="Search" Command="{Binding SearchCommand}"/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

注意KeyBinding和Button的Command属性是如何绑定到SearchCommandViewModel中的同一个Command()的.这有利于重用,还有助于保持ViewModel中的实际逻辑,具有所有优点(可测试性等),同时保持视图干净和无代码.