c# - 什么时候为 WPF/MVVM 使用事件和命令?

标签 c# wpf events mvvm command

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

什么时候使用命令合适?

最佳答案

Commands在 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
    }
}

还有你的观点:

<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>

请注意 KeyBinding 和 Button 的 Command 属性如何绑定(bind)到 ViewModel 中的同一命令 (SearchCommand)。这有助于重用,还有助于在 ViewModel 中保留实际逻辑及其所有优点(可测试性等),同时保持 View 干净且无代码。

关于c# - 什么时候为 WPF/MVVM 使用事件和命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17035372/

相关文章:

c# - MVVM 和控件创建

找不到 WPF 资源

java - 制作一个将绘图添加到 JFrame 的按钮

c# - 验证采集通过

c# - 内联组合数组 - LINQ

c# - NUnit 断言事件。有什么建议吗?

c# - 当绑定(bind)到 'SelectedItem' 时,如何让 Combobox 设置 null 值?

c# - 如何在 WPF Web 浏览器中获得相当于 CTRL-A/CTRL-C 的功能

python - 在 Python 中使用事件监控系统

Winforms TabControl 导致 UserControl 的虚假 Paint 事件