0

I'm in the early phases of developing a WPF application (using the MVVM pattern) that will allow the user to create a flowchart for a process.

The preliminary view looks as follows: enter image description here

The symbols in the left-hand pane are WPF Path objects.

What needs to happen is that the user must be able to drag a symbol from the symbol panel onto the diagram portion.

Now this is all very simple to do in straight WPF with code-behind events, but I need suggestions on how to implement this using the MVVM pattern. I presume that in my model I will have an Observable collection that contains all the symbols dragged onto the canvas(?). How would I then update that collection every time a symbol is dragged onto the canvas?

I understand that ideally, the view's code-behind must be completely empty when using MVVM, but would it break the pattern if I place code there that exclusively handles events on the view?

Any help would be appreciated.

user823486
  • 139
  • 3
  • 9

2 Answers2

1

In your canvas' ViewModel, define a property

public ObservableCollection<SymbolViewModel> Symbols { get; }

and in your view use an ItemsControl to display the symbols:

<ItemsControl ItemsSource="{Binding Symbols}" ... />

Of course, you need proper data templates, item templates and item panels defined in your ItemsControl.

The ObservableCollection implements INotifyCollectionChanged which ensures that the ItemsControl is automatically updated.

  • You've given me a few pointers, thanks. Any suggestions on how to implement the drag functionality from the Symbols panel onto the Diagram canvas? – user823486 Jun 07 '12 at 07:18
  • Use WPF's DragDrop.DoDragDrop() to start the drag operation and in the Drop event handler of the canvas, use DragEventArgs.GetPosition() to determine the mouse position where the symbol should be placed. –  Jun 07 '12 at 07:25
1

If you are asking about how ANY events fit into the MVVM then you must remember that MVVM is about abstracting View from ViewModel and Model i.e. View is unaware of what its ViewModel is and what the underlying Model is.

So sticking to this idea, there are 2 points of view.

1. If a view based event is handled in the code behind of the view (such as in `MyView.xaml.cs`) then as long as it does not refer the model or the viewmodel, it is perfectly fine in MVVM. Because such event handler is strictly a `View` specific code and should remain confined in the View layer (XAML or XAML.CS).

2. If an event handler has to refer the model or the viewmodel then it should not be handled in the code behind of the view but should be converted into `Command` based behavior using Attached Properties.

For you dragdrop scenario I would prefer way no 2. Google for attached properties and MVVM w.r.t. Events, you will find good examples.

WPF-it
  • 19,625
  • 8
  • 55
  • 71