Haven't heard about the famous WPF and Silverlight MVVM design pattern yet?
Well, I have one think to say about it:
“MVVM is like women, complicated but necessary. You can’t live with it and you can’t live without it”…
This time I want to concentrate on how to create a WPF shape editor custom control which works perfectly with the lovely MVVM design pattern.
Lets say that you want be able to draw shapes on top of Video, Image or whatever, but this time you have a view-model behind which contains and manages shapes-data.
Now the problem is: you don’t want your view-model dealing with UI elements or mouse/keyboard and other related UI events.
So one option is to create Attached Behavior, attach it to your custom control (which raises routed events), and translate the events into relevant commands.
Another option is to design your custom control to work with commands instead of events, or maybe both to be on the safe side.
Example of usage:
Ok, so what we have here is ShapeEditorControl contained in the visual tree of our view, which has a bindable GeometriesSource property bound with the geometry collection of the view-model. Another IsDrawingEnabled bool property which indicates whether we are in editing mode or not and instead of having RoutedEvent notifying that a shape was created by the control itself we have the EndDrawing property of type ICommand which currently bound with our view-model EndDrawingCommand property of type ICommand.
Each time you create a shape, draw it and finally close it, the corresponding command is executed by the control itself with the relevant Geometry. At the end, the view-model adds the new geometry to an ObservableCollection and the ShapeEditorControl is populated with the new geometry. There is an option to select the DataTemplate which finally renders the Geometry.
Have to say that this is only an example of designing custom control which perfectly works with the MVVM pattern and data binding.
Now that you have an idea, feel free to download this demo from here, and keep going…
Update: If you running vs 2008, download this.