Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use event and command for WPF/MVVM?

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?

like image 331
Ayda Sayed Avatar asked Dec 20 '22 04:12

Ayda Sayed


1 Answers

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.

like image 185
Federico Berasategui Avatar answered Jan 02 '23 22:01

Federico Berasategui