View first Approach

Jan 3, 2011 at 4:18 AM
Edited Jan 3, 2011 at 5:16 AM

Hi,

I am using MMVM with MEF. I am planning to use a View first approach, where the View is created first and then automatically View Model gets created.

But the conceptual problem I am facing here, is that if I have to pass some parameter from View to View model. Is this possible in MEF?

public partial class MyView : UserControl
    {

        public MyView ()
        {
            InitializeComponent();
        }

      
        [Import]
        [SuppressMessage("Microsoft.Design", "CA1044:PropertiesShouldNotBeWriteOnly", Justification = "Needs to be a property to be composed by MEF")]
 MyViewModel ViewModel
        {          
            set
            {
                this.DataContext = value;               
            }
        }
    }

Now say, I have a member variable 'Name' in VM. Is it possible to initialize it from View?

 

 

 

regards,

Indro

Feb 4, 2011 at 3:30 PM
Edited Feb 4, 2011 at 8:57 PM

Why would you want your View to initialize data in your ViewModel? Just because the View is initialized first does not mean ipso facto that the View is responsible for handing all required data to the ViewModel.

Normally you would do something akin to the following:

public interface IMyView : IDisposable { }

[Export(typeof(IMyView))]
public partial class MyView : IMyView
{
   public MyView() { InitializeComponent(); }
   [ImportingConstructor]
   public MyView(IMyViewModel model) : this() 
   { 
      DataContext = model; 
   }
   ~MyView() { Dispose(false); }
   private bool _isDisposed;
   public void Dispose()
   {
      GC.SuppressFinalize(this);
      Dispose(true);
   }
   protected void Dispose(bool disposing)
   {
      if(_isDisposed) return;
      if(disposing) 
      { 
         ((IDisposable)DataContext).Dispose();
         DataContext = null;
      }
      _isDisposed = true;
   }
}

public interface IMyViewModel : IDisposable { }
[Export(typeof(IMyViewModel))]
public class MyViewModel : IMyViewModel
{
   [ImportingConstructor]
   public MyViewModel(IMyRepository repository) { /* */ }  
}

public interface IMyRepository : IDisposable { }
[Export(typeof(IMyRepository))]
public class MyRepository : IMyRepository { }

The only thing that needs to know about any of the data is the IMyRepository instance. The only thing that needs to know how to manipulate those data is the IMyViewModel instance, and the only thing that needs to know how those data are displayed is the IMyView instance.