Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

6. MVVM > Using MVVM Light to enable MVVM applications

Using MVVM Light to enable MVVM applications

Using MVVM Light to enable MVVM applications Applies to Silverlight 3, 4, 5 and WP7 Not all necessary building blocks are available out of the box in Silverlight when you want to start using the MVVM pattern. Certain base classes and/or components have to be written—your basic ViewModel classes, ICommand implementations, a way to connect your View to your ViewModel, a way to communicate between ViewModels, and so on. Doing all of this by yourself would quickly result in quite a workload. Due to the popularity of the pattern, quite a few MVVM-enabling frameworks have popped up, of which the best-known are probably Caliburn, Prism (more than just MVVM), and the MVVM Light Toolkit by Laurent Bugnion. In this recipe (and the following ones), we will use the MVVM Light Toolkit to enable MVVM in our projects: it's open, it's lightweight, it's extensible, and it's very easy to use with little to no learning curve. Instead of using project templates (delivered with the MVVM Light Toolkit), we will only use the base classes in these recipes, so as offer a better understanding of how things work and can be set up. Getting ready We're going to recreate the application from the previous recipe, Creating a basic MVVM application, but this time by using the MVVM Light Toolkit base classes. This means you might have to download the necessary files and install them. They can be found at http://mvvmlight.codeplex.com/. You can start with the provided starter solution, which already includes these necessary dependencies: Chapter 6\Using_MVVMLight_Starter. The completed solution can be found at Chapter 6\Using_MVVMLight_Completed. How to do it... We're going to create an MVVM application that will display a list of persons and allows us to add a Person to that ListBox. To achieve this, we'll complete the following steps: Add a new class to the ViewModels folder in MVVM.Client. Right-click the folder, select Add | New class, and create a new class named PersonViewModel, inheriting ViewModelBase.Add the following using statements to this class: using GalaSoft.MvvmLight; using MVVM.Client.Models; Add two properties to PersonViewModel: private ObservableCollection<Person> _people; /// <summary> /// The People property /// </summary> public ObservableCollection<Person> People { get { return _people; } set { _people = value; RaisePropertyChanged("People"); } } private DateTime? _lastAddedDate; /// <summary> /// The LastAddedDate property /// </summary> public DateTime? LastAddedDate { get { return _lastAddedDate; } set { _lastAddedDate = value; RaisePropertyChanged("LastAddedDate"); } } Change the constructor of PersonViewModel and add the LoadData() method: public PersonViewModel() { LoadData(); } private void LoadData() { People = DataLoader.GeneratePeople(); } Add the AddPerson method to PersonViewModel: public void AddPerson() { People.Add(new Person() { FirstName = "Sven" , Name = "Vercauteren" , Age = 25 }); LastAddedDate = DateTime.Now; } Open PeopleView.xaml, and implement the bindings to LastAddedDate and People such as: <Grid x:Name="LayoutRoot"> <Grid.RowDefinitions> <RowDefinition Height="Auto"></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <StackPanel Orientation="Horizontal"> <Button x:Name="btnAddPerson" Content="Add person" Width="200" Height="30" Click="btnAddPerson_Click"></Button> <TextBlock Text="{Binding LastAddedDate, StringFormat='Last person was added on {0}', FallbackValue=''}" Margin="10,0,0,0"> </TextBlock> </StackPanel> <ListBox ItemsSource="{Binding People}" Grid.Row="1"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Vertical"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Name}" /> <TextBlock Text="{Binding FirstName}" Margin="5,0,0,0" /> </StackPanel> <TextBlock Text="{Binding Age}" FontSize="12" /> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </Grid> In the constructor of PeopleView.xaml.cs, set its DataContext to an instance of PersonViewModel: public PeopleView() { InitializeComponent(); this.DataContext = new PersonViewModel(); } Add the following using statement to PeopleView.xaml.cs: using MVVM.Client.ViewModels; Implement the click handler of btnAddPerson in PeopleView.xaml.cs: private void btnAddPerson_Click(object sender, RoutedEventArgs e) { ((PersonViewModel)DataContext).AddPerson(); } You can now build and run the application, and add a Person by clicking the Add person button. How it works... We've started out by creating the PersonViewModel class, which inherits MVVM Light's ViewModelBase class. Among other things (which will be talked about in later recipes), this ViewModelBase class implements INotifyPropertyChanged. Through this interface, notifications can be sent when a property is changed, telling Silverlight that the UI should be updated (this of course depends on how you've created your bindings). In the PersonViewModel class, we've added two properties: People (an Observable Collection<Person>) and LastAddedDate. Both properties raise the NotifyChanged event in their property setters, which makes sure the UI is updated when these properties are set or changed. The starter solution already includes a Person class (inheriting NotifyProperty ChangedBase, which implements INotifyPropertyChanged). This is the business object that is our model. In the PersonViewModel, we fill this with dummy data by calling DataLoader.GeneratePeople() via the constructor. On to the View—PeopleView. PeopleView contains a ListBox, bound to the People collection, and a TextBlock, bound to the LastAddedDate. In the View's constructor, the DataContext of the View is set to a new instance of our PersonViewModel class. This is crucial; as the DataContext of PeopleView is now a PersonViewModel instance, our binding syntax to properties on the PersonViewModel works. In an MVVM pattern, the ViewModel is always the DataContext of the View. There's also a button, btnAddPerson, defined on the View. When this button is clicked, the method AddNewPerson() is executed on the ViewModel. This adds a new Person to the People list, and sets the LastAddedDate to the current date. Bringing it all together, it works as follows: The View is instantiated, and its DataContext is set to a new PersonViewModel instance.In the constructor, the People collection of PersonViewModel is initialized. The ViewModel is thus responsible for converting the Model (the Person class) to a representation that is useable by the View. Sometimes, the ViewModel is called a converter on steroids—the reason is obvious.As the properties on the ViewModel fire a NotifyChanged event in their setters, the View (which is bound to these properties) is correctly updated.When the Add Person button is pressed, a Person instance is added to People, and the LastAddedDate is changed. The View is notified of this change (thanks to the INotifyCollectionChanged and INotifyPropertyChanged interfaces) and is, again, updated accordingly. There's more... This is just the beginning, we've now got a very basic MVVM application up and running, but a few crucial features are still missing—connecting the View to the ViewModel can be done differently (built-in in MVVM Light), Commanding can be used to bind Events to Commands in the ViewModel, and there's a way to send messages between ViewModels. Make sure you read the next recipes for a better understanding of these concepts. See also For more information on MVVM, have a look at the other recipes in this chapter.

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint