我正在练习如何使用 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/