Question

In MEFedMVVM viewmodels are instantiated using ViewModelLocator. MEFedMVVM is really powerful, since you can have an arbitrary constructor for your viewmodels:

[ExportViewModel("MyViewModel")]
public class MyViewModel : NotifyPropertyChangedBase
{
    [ImportingConstructor]
    public MyViewModel(IMediator mediator, IContainerStatus containerStatus, IDispatcherService dispatcherService)
    {
    }    
}

IMediator, IContainerStatus and IDispatcherService are service interfaces which are instantiated through MEF. Obviously, I can create my own services if needed.

The problem

When my view has loaded it needs to assign a member of one of its children's readonly property with data from the viewmodel. Ideally, I would bind this variable directly in XAML, but I cannot do that since the property is readonly and its member is not an attachable property. Currently, I have an ugly workaround:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var viewModel = DataContext as MyViewModel;
    this.child.SomeReadonlyProperty.Data = viewModel.MyData;
}

I want to get rid of this coupling of the view and the viewmodel. Both MEFedMVVM and Prism provide different patterns that might be helpful, but I have no idea which to use - and how. Is it ok to let services have access to both the view and the viewmodel?

Q: What pattern should I use to remove the coupling?

Was it helpful?

Solution

I think I would be inclined to create an interface which your view can implement that will describe the behavior you need to set the property:

interface IMyView
{
    void SetReadOnlyProperty(object value);
}

You can then create your implementation of SetReadOnlyProperty in the view, export the view as type IMyView and finally, create an import on your viewmodel of type IMyView which will expose your method and allow you to perform calls from the viewmodel. I believe this doesn't go against the ethos of MVVM because the viewmodel isn't aware of the view, it just has an interface that will expose what you need.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top