ICommand discovery with MEF

Sometimes you are in ViewModel X and you want to execute a command on ViewModel Y. You do not want to link the 2 because of some constrains that that might impose. How can you leverage MEFs capabilities to overcome such a situation?

Easy have the ViewModel Y expose the command as a property just like you would have it for binding from the View, but also add an Export attribute on the property and give it a name

image

 

Now from ViewModel X simple imports the ICommand by specifying that same name (yes you can have the string as a constant, also I would advice to use constants to avoid conflicts in strings)

image

 

MEF will automatically get the command from ViewModel Y into ViewModel X for you. This works very nicely with MEFedMVVM since MEFedMVVM resolves all ViewModels via MEF thus you do not need to do anything to resolve the ViewModel or anything. You simply decorate the properties for Export and Import and viola you can start drinking beer Smile

Happy coding Smile

5 thoughts on “ICommand discovery with MEF

  1. Say you have two viewmodels

    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    pub class ViewModel1
    {
    [Export(“VM1Command”)]
    public ICommand VM1Command {get; set;}
    }

    [Export]
    [PartCreationPolicy(CreationPolicy.NonShared)]
    pub class ViewModel2
    {
    [ImportingConstructor]
    public ViewModel2([Import(“VM1Command”)] ICommand vm1Command) {}
    }

    Now assume ViewModel1 and ViewModel2 get created and they are bound to say View1 and View2.

    When ViewModel2 is being created it sees that it needs to import the VM1Command from ViewModel1, and it ends up creating a new instance of ViewModel1 (goes into ViewModel1’s constructor). So now when you try to call vm1Command from ViewModel2 it will execute that command on the new instance of ViewModel1, which is actually not the one bound to View1.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s