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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With