Following is excrept fro开发者_运维百科m this article on MVVM. Can someone provide example of how these other patterns (command, DI) are used in WPF? Are there any other desgin patterns that are used in WPF that you don't see listed here ?
There are other patterns you should be aware of to assist you in MVVM. Patterns like commanding (baked into WPF, solutions for SL), mediator and gasp dependency injection. .
I've written the article about some of them: WPF and Silverlight design patterns
Here is a brief description of the patterns:
1) MVVM - used as a model converter and as a replacement of the code-behind. Improves testability, it is much easier to write unit tests for ViewModel.
2) Dependency Injection - used for improving testability of a class (you can write unit tests for a specific class separately from others) and for the possibility to change implementation in easier way (change a logger, cache provider, web service etc)
3) Command - can be applied to Button and MenuItem controls by default, disables controls if an action can't be executed. Also used in MVVM pattern as a replacement of code-behind events.
Other patterns from the classic book which are already used in WPF:
- Singleton. The Application class in WPF and the HttpContext class in Web forms.
- Adapter. The data-binding engine, which uses the IValueConverter interface to convert binding values for the UI.
- Decorator. The Border class, which decorates any UIElement class with a border of variable thickness and color.
- Façade. The PrintDialog class, which provides a simple interface that enables you to use the entire printing and document subsystem that WPF provides.
- Command. The ICommand interface, which is implemented by the RoutedCommand and RoutedUICommand classes.
- Iterator. The IEnumerator interface, which many collections and lists in the .NET Framework implement.
- Observer. The INotifyPropertyChanged interface and events.
Data binding (between View and ViewModel) uses the Observer pattern. Also: the Factory pattern can be used to instantiate the ViewModel but that is optional.
Setter dependency injection:
When using MVVM you have to inject an instance of ViewModel into the View by setting it to the view.DataContext property:
var viewModel = new CustomViewModel();
var view = new CustomView();
view.DataContext = viewModel;
精彩评论