how to parametrize an import in a View?

Posted by Gianluca Colucci on Stack Overflow See other posts from Stack Overflow or by Gianluca Colucci
Published on 2010-06-07T11:38:09Z Indexed on 2010/06/07 11:42 UTC
Read the original article Hit count: 291

Filed under:
|

Hello everybody,

I am looking for some help and I hope that some good soul out there will be able to give me a hint :)

In the app I am building, I have a View. When an instance of this View gets created, it "imports" (MEF) the corresponding ViewModel.

Here some code:

public partial class ContractEditorView : Window
{
    public ContractEditorView ()
    {
        InitializeComponent();
        CompositionInitializer.SatisfyImports(this);
    }

    [Import(ViewModelTypes.ContractEditorViewModel)]
    public object ViewModel
    {
        set
        {
            DataContext = value;
        }
    }
}

and here is the export for the ViewModel:

[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(ViewModelTypes.ContractEditorViewModel)]
public class ContractEditorViewModel: ViewModelBase
{
    public ContractEditorViewModel()
    {
        _contract = new Models.Contract();
    }
}

Now, this works if I want to open a new window to create a new contract... But it does not if I want to use the same window to edit an existing contract...

In other words, I would like to add a second construct both in the View and in the ViewModel: the original constructor would accept no parameters and therefore it would create a new contract; the new construct - the one I'd like to add - I'd like to pass an ID so that I can load a given entity... What I don't understand is how to pass this ID to the ViewModel import...

Thanks in advance, Cheers, Gianluca.

© Stack Overflow or respective owner

Related posts about MEF

Related posts about mvvm-light