Yesterday I started working on a new plug-in model for Comicster, such that a plug-in "tool" could appear as a new menu item under the "Tools" menu. You can read more about the results here.
When I first wrote the
ITool interface, I gave it a method like this:
void Execute(Item selectedItem);
So when the tool was executed, the only thing it had access to was the currently active item in the main window.
I soon realised that my plug-in was updating the open collection and would need some way to tell Comicster that the file had been modified, so that the user would be prompted to save when they exited the app. Hoping to get something working without having to change the method signature, I struck upon an idea.
As the author of the application, I knew that the main window had a ViewModel behind it with a
Content property. I knew that if there was a collection open, that property would be set to an instance of
CollectionViewModel, which in turn has an
IsModified property. So I wrote some nasty code:
dynamic vm = Application.Current.MainWindow.DataContext; vm.Content.IsModified = true;
Can you see what it's doing? Because I'm getting hold of the main window's DataContext as a dynamic object, I'm able to do a runtime lookup of the properties without knowing the type! It actually worked a treat!
I don't recommend this, and I've since refactored the plug-in architecture so that plug-ins get passed an
IToolContext instance that has the properties they need, but I did think that this was an interesting use for the dynamic feature of C# 4.
- Dew Drop – June 3, 2011 | Alvin Ashcraft's Morning Dew | http://www.alvinashcraft.com/2011/06/03/dew-drop-june-3-2011/
- Stupid Dynamic Tricks « Mas-Tool's Favorites | http://mas-tool.com/?p=2758