什么时候使用事件和命令为WPF / MVVM? [英] When to use event and command for WPF/MVVM?

查看:73
本文介绍了什么时候使用事件和命令为WPF / MVVM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习如何使用MVVM模式编写WPF应用程序。到目前为止我没有在我的代码中使用命令。在我的Viewmodel中,我实现 INotifyPropertyChanged 并使用(事件 PropertyChangedEventHandler PropertyChanged )来触发事件。



什么时候适合使用命令?

解决方案

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



这里有一个基本示例: p>

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



你可以这样定义你的ViewModel:

  public class MyViewModel:ViewModelBase 
{
public string SearchText {get; set;} // NotifyPropertyChanged等

public Command SearchCommand {get; set;}

public MyViewModel b $ b {
//实例化命令
SearchCommand = new DelegateCommand(OnSearch);
}

private void OnSearch()
{
// ...基于SearchText执行搜索
}
}

您的视图:

 < StackPanel> 
< TextBox Text ={Binding SearchText,UpdateSourceTrigger = PropertyChanged}>
< TextBox.InputBindings>
< KeyBinding Key =EnterCommand ={Binding SearchCommand}/>
< /TextBox.InputBindings>
< / TextBox>
< Button Content =SearchCommand ={Binding SearchCommand}/>
< / StackPanel>

注意 KeyBinding code> Command 属性都绑定到ViewModel中的同一命令( SearchCommand )。这有助于重用,并且有助于保持ViewModel中的实际逻辑及其所有的好处(可测性等),同时保持视图干净和无代码。


I am practicing on how to write a WPF application with MVVM pattern. So far I haven't used command in my code. In my Viewmodel I implement INotifyPropertyChanged and used (event PropertyChangedEventHandler PropertyChanged) to fire events. Why do I feel like I still miss some concept of WPF about how to use command?

When is it appropriate to use commands?

解决方案

Commands in WPF are used to abstract an user-triggered action (such as clicking a Button or pressing a key.

here's a basic example:

Suppose you want to search for employees in your database when the user clicks the "Search" button, or hits the enter key while focusing the Search Box.

You might define your ViewModel like this:

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

And your View:

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

Notice how the KeyBinding and the Button's Command property are both bound to the same Command (SearchCommand) in the ViewModel. This facilitates reutilization, and also helps keep actual logic in the ViewModel, with all its goodness (testability, etc), while keeping the view clean and code-less.

这篇关于什么时候使用事件和命令为WPF / MVVM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆