Saturday, October 17, 2009

Finally a Simple MVVM in Silverlight

So a week or so ago I ran across this article/post by Jeremiah Morrill (MVVM-for-Tarded-Folks-Like-Me-or-MVVM-and-What-it-Means-to-Me.aspx ) was agasp that some spent the time to make MVVM so understandable. What will I do now that everyone can understand MVVM? I pinged Jeremiah and he was open to making this a framework on codeplex seeing as there are only 35 versions of MVVM frameworks out there already albeit no matter how good they are they usually include bits that have todo with 5 or 7 other design patterns so lets take a look at building an MVVM app with just the Simple Framework for MVVM. To start with the Simple framework consistes of one class with three lines of real code:

public class TardViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;

public void InvokePropertyChanged(string propertyName)
{
var e = new PropertyChangedEventArgs(propertyName);
PropertyChangedEventHandler changed = PropertyChanged;
if (changed != null) changed(this, e);
}
}

I know I know its a work of art but this really is all you need. Now using this class is just as simple to create an MVVM application using the simple framework. First create a model class like so:

public class AModelClass
{
// super easy version
public string SomeValue { get; set; }
}

ok so maybe also make it return some data magically. Next you need to create your complex view model class that inherits from ViewModelBase like so (WARNING: this is the complicated part...)

public class AViewModelClass : ViewModelBase
{
private AModelClass MyModel;

public AViewModelClass()
{
MyModel = new AModelClass();
}

public string SomeValue
{
get { return MyModel.SomeValue; }
set
{
if (MyModel.SomeValue != value)
{
MyModel.SomeValue = value;
InvokePropertyChanged("SomeValue");
}
}
}
}

So now we have a model that returns some data and then we have our view model that we can bind do. Now to create a View (ie user control) with xaml akin to this:

>UserControl.DataContext<
>Simple:AViewModelClass /<
>/UserControl.DataContext<
>Grid x:Name="LayoutRoot" Background="White"<
>TextBox Text="{Binding SomeValue, Mode=TwoWay}" /<
>/Grid>

If you really like you can get extra complicated and load view in shell or whatever in Xaml like so:

>simple:AViewClass /<

so some other fancy thing... but that is all it takes to have some Model View View Model going on. Nice simple...

http://simple.codeplex.com/

stay tuned for maybe commanding for tards...

No comments:

Post a Comment