c# – MVVM, Shared Model и паттерн Repository


There is a WPF MVVM application that displays Shape within a Canvas.

Simplified version for ease of presentation:


class Canvas
    public List<Shape> Shapes;

class Shape
    public int X;
    public int Y;

There are several ViewModels, some of them display the data of the selected shape (the shape is selected by clicking on the shape), some – the data of the selected Canvas (selected using the combobox in the ToolbarView), some – both.

That. there is a CanvasViewModel, CanvasPropertiesViewModel, ShapePropertiesViewModel, ToolbarViewModel.

The ToolbarViewModel, CanvasViewModel, and CanvasPropertiesViewModel are associated with the current Canvas. The ToolbarViewModel and ShapePropertiesViewModel are associated with the selected shape. The ToolbarView associated with the ToolbarViewModel displays a large flat list of all canvas names.

Question 1: How to fumble between the ViewModels of the selected shape and the selected canvas? Tried it through EventAggregator, but there are too many message registrations, the code becomes unreadable.

Question 2: Who should be responsible for downloading and saving data from the server about the canvas? And where is it better to place this logic (can somehow use Repository)? (there is a third-party web service that gives and stores data about the canvas)


First, if Canvas is somehow justified, then ToolbarViewModel is not. The toolbar is a detail of the View, and the meaning of this VM is the root display parameters.

Thus, we class RootVM with a class RootVM with ReadOnlyCollection<CanvasVM> Canvases and DP CurrentCanvas . To which it is easy to attach a combobox or there is a ListView .

Then, I would CanvasViewModel and CanvasPropertiesViewModel , they seem to be responsible for the same entity.

Let's see which of your VMs really needs CurrentCanvas . ToolbarViewModel contains it. CanvasViewModel exists for every canvas, and shouldn't know about CurrentCanvas at all. And CanvasPropertiesViewModel we merged with CanvasViewModel .

The problem is gone!

Now, about loading / unloading from the server. Model objects are responsible for this (by class to Canvas and a shape). The decision about loading and unloading is made in any case by the business logic, so it should command the model to exchange information. Well, the VM is responsible for synchronizing data with the model.

Do not be afraid that one VM is displayed in several places with several different Views, and in different ways. This is normal practice.

Scroll to Top