开发者

how to parametrize an import in a View?

开发者 https://www.devze.com 2023-01-02 18:46 出处:网络
I am loo开发者_如何学Pythonking for some help and I hope that some good soul out there will be able to give me a hint :)

I am loo开发者_如何学Pythonking for some help and I hope that some good soul out there will be able to give me a hint :)

I am building a new application by using MVVM Light. In this application, when a View is created, it instantiates the corresponding ViewModel by using the MEF import.

Here is 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 in order to create a new contract... or in other words, it is perfect if I don't need to pass the ID of an existing contract.

However let's suppose I want to use the same View in order to edit an existing contract. In this case I would add a new constructor to the same View, which accepts either a model ID or a model object.

"Unfortunately" the ViewModel is created always in the same way:

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

As far as I know, this invokes the standard/no-parameters constructor of the corresponding ViewModel at composition-time.

So what I would like to know is how to differentiate this behavior? How can I call a specific constructor during composition time? Or how can I pass some parameters during the Import?

I really apologize if this question sounds silly, but I have only recently started to use MEF!

Thanks in advance,

Cheers, Gianluca.


You CAN do this. Check out the Messenger implementation in MVVM-Light. You can pass a NotificationMessage(Of Integer) to send the right ID to the view model. The view model has to register for that type of message, and load it when a message is sent.

MEF Imports by default only have a parameterless constructor.

0

精彩评论

暂无评论...
验证码 换一张
取 消