C# Disciples

my life in Avalon ….

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

About these ads

February 17, 2011 - Posted by | MEF, MEFedMVVM, mvvm, tips and tricks

5 Comments »

  1. This would probably not work if both the view models are marked as NonShared

    Comment by Ganesh | February 18, 2011 | Reply

  2. MEF is great for modular application development.

    Comment by Oleh Mykhayloych | February 20, 2011 | Reply

  3. have you head about it in the Prism?

    Comment by @dufagundes | March 1, 2011 | Reply

  4. I do not know what you mean…

    Comment by marlon grech | March 1, 2011 | Reply

  5. 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.

    Comment by Ganesh | March 10, 2011 | Reply


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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 845 other followers

%d bloggers like this: