/* BeejBlog */

The Essence of WPF ViewModel

I think this guy (scroll down to comments) is concisely nailing the real core implementation detail of what ViewModel is all about vs old school approaches… everybody else just seems to have a bunch of “it’s great” double speak:

Another thing...
The one big paradigm shift I experienced when moving to WPF is realizing that if you front units of your business logic with DependencyObject "controllers" you can pretty much remove all codebehind in your UI. For instance imagine this common scenario:
You want to display a list of products in a category, you have a category dropdown and a products list in the UI. In your business logic, you have a method that returns a list of categories and a method that returns a dataset of products based on a category name.
Normally, you'd have to add codebehind for the form load event to populate the dropdown from the business logic, then on the slelectedindexchanged event of the dropdown etc blah blah yadda yadda.
But in WPF, you can create a DependencyObject "controller" that exposes a dependency property for the category list and the product list, implemented as observable lists. Inside this controller, you populate the category list when instantiated. Then you listen for the selected value of the category to change, at which point you populate the products list. All you have to do at that point is to databind against these properties in the UI. Its a nice pattern, and pretty easy to unit test both the UI and the controller.

Dang! these guys are all over it:

Scott - Imagine a world where any POCO could actually be represented as a control in WPF. That's what DataTemplate does for you.
To use a DataTemplate in this way, create a DataTemplate element in your Window/Application/whatever's Resources, and set the DataType to whatever type the template is for (don't specify an x:Key attribute).


The DataTemplate can have a single child, which should be some sort of control/gui object (like a Grid), and all descendants of the DataTemplate will implicitly have their DataContext set to whichever object is being templated.


Once you've done this, you can drop instances of your templated type anywhere you could normally have a control, and WPF will automagically find and apply the template.


Another way to use DataTemplates is to specify a key on them (at which point the DataType attribute becomes optional but often recommended) and then specify that resource on various properties that accept datatemplates, like the ItemTemplate property on ComboBox or the ContentTemplate property on ContentPresenter (you can use ContentPresenter in places where you'd like to refer to an existing object instead of creating a new one--for example, you could leave your settings object in the resources, and have a ContentPresenter with its Content set to that object).