The wrong “solution”
On of these problems is keeping the MVVM pattern in tact when a view does not support bindings. People don’t know how to handle the stuff, and basically come up with the following “solution” (it’s a real-world solution I’ve seen, but I’ve simplified it a bit and took the part where UI elements are used inside the view-model):
public class MainPageViewModel : ViewModelBase
{
{
public ICommand Navigate { get; private set; }
private void OnNavigateCommand(string request)
{
if (screenControl == null)
{
DeskTopContent.Children.Add(screenControl);
ObservableCollection<TaskBarItem> taskBarItemsList = (ObservableCollection<TaskBarItem>)TaskBarItemsSource.Source;
TaskBarItem item = new TaskBarItem(screenControl, request);
...
...
When I see such code, I always ask two simple questions:
- What is the best argument for MVVM? (they probably answer: loosely coupled design and testability)
- How are you going to unit test the view model above? (they probably answer: not)
The right solution
Sometimes, when using controls that do not support MVVM bindings, you want to implement something specific, but don’t break the pattern. An excellent example of this is to use the Image control as a button. There are other solutions such as the EventToCommand behavior to solve this specific case, but this example should be easy to understand for everyone. A different example (which is a bit more complex) is for example a GridView that returns IEnumerable<GridRow> instead of a model in the ItemsSource property of the grid. However, using this as an example would make it all a bit more complex than needed.
Read more: Geert van Horrik
QR: