简体   繁体   中英

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?

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.

The fun thing is that using original Commands concept from WPF is absolutely not required :). You could build large and complex applications with all that beauty of loosely coupled design (xaml) and business logic (c#/vb code) in place with just using MVVM all around and free open source application framework library Caliburn.Micro .

Disclaimer : I'm just a happy user of this library and have nothing to do with its creators, so this is not paid ads or something like that.

Please, just take a look over this very basic sample from official documentation :

--> Basic Configuration, Actions and Conventions <--

and you will fill the power of binding events from you XAML view directly to methods in your C# view-model without mess of proxy code for commands declaration and registration (like this is implemented in other similar application frameworks).

And never mind that this sample is Silverligh app - Caliburn.Micro support all major Xaml platforms almost the same way and the WPF sample will looks pretty like above Silverlight-based.

In addition to the mentioned major capability (buinding to methods) Caliburn.Micro have:

  • handy predefined naming conventions for binding that leaves your XAML files clean and readable (and yet still design-time friendly!)
  • base implementation of INotifyPropertyChanged so that you could just inherit from it all of your view-models
  • base classed for implementation of frequently used scenarios like:
    • master-details
    • parent-child
    • list-with-selected-items
  • EventAggregator for even more loosely coupled communication between view-models and other classes
  • loosely coupled support for things like keyboard focus and windows management (for WPF)
  • and a bit more :)

Just give it the chance and you will never need vanilla WPF Commands ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM