Reputation: 133
I am reading about MVVM in order to adopt this across my presentation layers' views. Ideally I would like to use the same approach for WinForms, ASP.NET and SL.
I came across 2 distinct approaches and I would like to gather opinions in these (and possibly others):
The 'View with interface' and where the View is databound to the ViewModel
In this approach we have an interface IView that contains: - Set/Get properties for the typical field values - Events for actions that happen on the View
The way this works is by a concrete implementation of the IView being injected into the ViewModel. The ViewModel then wires up the
events. It also then 'pushes' and pulls field values via the properties. It is also aware of what happens on the View by means of
the events. Controls can be activated and deactivated through the IView properties.
Concrete implementations of the view is easy in WinForms, not sure about the other technologies and the 'Blendability' in SL.
public interface IMyView
{
event EventHandler SomeActionClicked;
Boolean CanEditField1 { get;set; }
string Field1 { get;set; }
}
public class MyConcreteView: Form,IMyView
{
public event EventHandler SomeActionClicked;
public Boolean CanEditField1
{
get { return edtField1.Enabled; }
set { edtField1.Enabled = value; }
}
public string Field1
{
get { return edtField1.Text; }
set { edtField1.Text = value; }
}
private void btnAction_Click(object sender,EventArgs e)
{
SomeActionClicked(sender,e);
}
}
public class ViewModel
{
public ViewModel(IMyView view)
{
this.view = view;
view.SomeActionClicked += SomeActionHandler;
}
private void SomeActionHandler(object sender,EventArgs e)
{
view.CanEditField = !view.CanEditField; // Or whatever 'state' the ViewModel or Model is
view.Field1 = DateTime.Now.ToString(...);
}
private IMyView view;
}
The other approach is a ViewModel that has several properties that reflect the Model (data/field values, UI control states, etc.
The View then uses databinding to 'present' the field values (Model) in the UI controls on the View. The ViewModel also controls
UI control states through properties being databound to. Actions in the View is fed to the ViewModel through methods in the
ViewModel that are hooked to.
Any (non-apparent) pros & cons to each of these methods?
Upvotes: 0
Views: 960
Reputation: 814
Maybe you would actually only need the view as a "presenter" of the properties in winforms, while in SL all the wiring up is done trough the xaml, that would require less boiler plate. So keep your view models in a common code base, while the view is specific to winforms. For ASP.NET, those viewmodel events are not so sweet to hook up, unless you go for ugly oldschool webforms controls and postbacks.
I dont really see the difference between the two approaches, both would work with SL.
Keep it simple.
Upvotes: 1