Implementing the RowViewModel – Part 2

Part 2 – Getting Data into the Grid

In Part 1, we setup the projects necessary for a standard business application using IdeaBlade DevForce for the Model, MVVM Light for the ModelView and a Telerik RadGridView in the View.

In Part 3, we will follow through the binding process to see some of the challenges posed when making the grid editable.

In Part 2, we will make the changes necessary to make the grid editable.

Requirements

For this part of the sample, the requirements are as follows:

  1. Show Orders in the Rows of the Grid.
  2. Make the Grid Editable.
  3. Save changes to the Orders with a Save Changes button.

Showing the Orders in the Grid

This will require adding an Orders property to the MainViewModel; populating that property and then binding the Orders property to the grid.

  1. Make sure there is a reference in the Web project to the server-side Model project.
  2. Open the MainViewModel.cs file.
  3. Remove the Welcome property.
  4. Open the ViewModel\MainViewModel.cs file.
  5. Use the mvvminpc Snippet to add an Orders property.
    /// <summary>
    /// The <see cref="Orders" /> property's name.
    /// </summary>
    public const string OrdersPropertyName = "Orders";
    
    private ObservableCollection<order> _orders;
    
    /// <summary>
    /// Gets the Orders property.
    /// TODO Update documentation:
    /// Changes to that property's value raise the PropertyChanged event. 
    /// This property's value is broadcasted by the Messenger's default instance when it changes.
    /// </summary>
    public ObservableCollection<order> Orders
    {
        get
        {
            return _orders;
        }
    
        set
        {
            if (_orders == value)
            {
                return;
            }
    
            //var oldValue = _orders;
            _orders = value;
    
            // Remove one of the two calls below
            //throw new NotImplementedException();
    
            // Update bindings, no broadcast
            RaisePropertyChanged(OrdersPropertyName);
    
            // Update bindings and broadcast change using GalaSoft.MvvmLight.Messenging
            //RaisePropertyChanged(OrdersPropertyName, oldValue, value, true);
        }
    }
  6. Next, add a method to fill the collection.
    private void GetOrdersAsync()
    {
        var em = new NorthwindIBEntities();
        var qry = em.Orders;
        em.ExecuteQueryAsync(qry, args =>
             this.Orders = new ObservableCollection<order>(args.Results));
    }
  7. Next, add a call to the new method in MainViewModel constructor:
    public MainViewModel() 
    { 
        GetOrdersAsync();
  8. Finally, add a binding to the XAML to show the Orders in the Grid.  (Set the ItemsSource of the RadGridView to Orders.)
    <telerik:RadGridView Name="radGridView1" ItemsSource="{Binding Path=Orders}" Height="775" Width="1000" />
  9. Build and Run.  After a moment or two, you should see the grid, fully populated with Orders.
    image

Making the Grid Editable

For once, the default behavior is desirable.  We get this for free because the RadGridView is editable by default.  Due to the magic of Binding, the Order objects are getting updated whenever a cell in the grid is edited.

Saving the Changes

Saving those changes will require us to have a button bound to an ICommand that will tell the EntityManager to save all the changes.

  1. In MainPage.xaml, add a button to the StackPanel above (or below) the RadGridView.
    <Button Content="Save" Height="23" Name="SaveAllButton" Width="75" HorizontalAlignment="Left" />
  2. In MainViewModel.cs, add a new RelayCommand named SaveAllCommand.
    public RelayCommand SaveAllCommand
    {
        get;
    	private set;
    }
  3. In the MainViewModel constructor, add a line to instantiate the command:
    SaveAllCommand = new RelayCommand(this.SaveAllOrders);
  4. Now add the SaveAllOrders method and the SaveAllButtonEnabled property:
    private void SaveAllOrders()
    {
        this.SaveAllButtonEnabled = false;
        _entityManager.SaveChangesAsync(args => 
            this.SaveAllButtonEnabled = true);
    }
    
    public bool SaveAllButtonEnabled
    {
        get
        {
            return _saveAllButtonEnabled;
        }
        set
        {
            _saveAllButtonEnabled = value;
            RaisePropertyChanged("SaveAllButtonEnabled");
        }
    }
  5. Now you can go back to the button to set the bindings:
    <Button Content="Save" Height="23" Name="SaveAllButton" Width="75" HorizontalAlignment="Left" IsEnabled="{Binding Path=SaveAllButtonEnabled}" Command="{Binding Path=SaveAllCommand}" />
  6. Build and Run. After a moment or two, you should see the grid, fully populated with Orders. Try editing some of the orders and hit Save All. Refresh the page to see that the changes were saved.

What’s next?

So now you have an editable grid. So far, we have not needed the RowViewModel. If you only want SaveAll functionality, the default behavior of the grid will suffice. The grid lets you edit any cell all the time and the bindings keep the model up to date. A simple call to entity manager to save the changes and all is well.
However, if you want some entity specific functionality, you will find it quite cumbersome to try to deal with this within the context of the grid’s ViewModel as it is really only concerned with the grid and entire grid related actions (such as Save All).

In Part 3, we will add some entity specific requirements so we can see how to use the RowViewModel to make working with the entities in the grid much simpler.

Implementing the RowViewModel – Part 1

 

Part 1 – Setting up the Projects

In my earlier post here, I introduced the concept of a RowViewModel to make editable grids using the MVVM pattern.  In this post, I will demonstrate how to implement the RowViewModel using a combination of IdeaBlade DevForce for the Model, MVVMLite for ViewModel support and Telerik’s Silverlight RadGridView for the View.

Prerequisites:

  1. IdeaBlade DevForce 6.0.7 or later.
  2. Telerik Silverlight Controls 2010.3 or later.
  3. MVVM Light Toolkit
  4. VisualStudio 2010 and Silverlight 4
  5. Silverlight 4 Toolkit

Assumptions:

  1. We’ll use IdeaBlade’s sample database:  NorthwindIB.  This can be found in the \Program Files\DevForce 2010\ folder.
  2. I have way too many VS add-ins installed so my screen shots may not appear as your screen does.
  3. I do use JetBrains Resharper and Telerik’s JustCode, so some of the refactorings and shortcuts may not be available if you do not have these tools.

Creating the Beginning State

  1. Per the article and sample shown at MVVM Light with DevForce, we will create a sample app using the MVVM Light SL4 template.  (I.e. Set up their MvvmLite1 example.)
    image
  2. Then add the DevForce Silverlight Application project.
    image
  3. Delete the README_FIRST files.
  4. In the Model project:
    1. Delete App.xaml and MainPage.xaml.
    2. Rename the project with SL suffix.  Do not rename the Assembly with the SL suffix and do not change the namespace.
  5. In the Application project:
    1. Add a reference to the Model project.
    2. Add references to the DevForce assemblies referenced in the Model project.
      image
    3. In the properties for the DevForce assemblies, change the Copy Local to True and the Specific Version to False.
      image
    4. Add a reference to System.Runtime.Serialization.
  6. In the Web project:
    1. Rename the web project to remove the word Model.
    2. In the project properties:
      1. Rename the Assembly and the namespace.
      2. On the Silverlight Applications tab, remove the dead DevForce Silverlight app project (if present).
        Add the Silverlight Application (e.g. RVMSample). 
    3. Delete the test HTML page and the Default.aspx page.
    4. Set the Web project as the Startup Project. 
    5. Set the new test ASPX page as the Start Page.
    6. Delete the XAP file from the ClientBin folder.
  7. Save and Close the solution.
  8. Rename the project folders to match the project names.
  9. Edit the .SLN file in a text editor to correct the folder names there too. 
    image
  10. Open the solution in VS.
  11. Build and Run.  Nothing so far has changed the functionality so it should work fine:   
    image    

Creating the Server-Side Model Project

So far so good.  We have setup the three-project solution.  Unfortunately, this means we’re going to load the EDMX into the Web project, which hardly seems fitting.  Let’s create a server-side project to house the server side Model.

  1. Add a regular Class Library project as the server side Model.  This should be named application.Model.
  2. Delete Class1.
  3. In the Web project, add a reference to the application.Model project.
  4. Add an ADO.Net Entity Data Model name it NorthwindIBModel.
  5. Select to Generate from database.
  6. Connect to the NorthwindIB database.
  7. Select the following tables:
    Customer
    Employee
    Order
    OrderDetail
    Product
  8. Change the namespace to application.Model.
  9. Wait while the Entity Manager and IdeaBlade do their code generation.  IdeaBlade will also make a link from the Model.SL project to the Model project so they share code.
  10. Copy the new connectionString settings from app.config in this project to web.config in the web project.
  11. Build the solution to make sure all the references are configured properly.  Run the app.  See nothing has changed yet. 🙂

Adding the Grid to the View

Great, now we have client-side (Model.SL) and server-side (Model) model projects, a Silverlight application project and a Web project to host it all in.  Let’s go ahead and add the Telerik Grid to the project, then we can finally start looking at the Row-View-Model pattern.

  1. In the application project, open the MainPage.xaml.
  2. Change the Width and Height of the page to 1000 x 800.
  3. Remove the TextBlock that is there.
  4. Change the <Grid> to a <StackPanel>.
  5. In the <StackPanel>, drag and drop a Telerik RadGridView from the Toolbox.
  6. Change the Width and Height of the RadGridView to 1000 x 800.
  7. Build the solution to make sure all the references are configured properly.
  8. Run the application.  You should see the empty Telerik grid in your browser:
    image

Ta da!  All that work to set up the beginning state for exploring RVM.  In my next posting, you will get the requirements for the grid and see how we can use the RowViewModel to make in-line grid editing much simpler.

MVVM and the Editable Grid

There is a dirty little secret in the Grid market:  making a Grid Editable, on a row-by-row basis (not in its entirety), is a nightmare.

So, as we all know, MVVM is the cure-all for everything UI, so apply MVVM to the Grid form and away we go.  Right? 

Doh!  Wrong.

You see, hosting the Grid in the View of a form actually ends up making the hassle even worse.  But do not despair, there is a simple-enough solution to this otherwise complex dilemmas.   I call this solution:  the RowViewModel.

The what you say?  Heretical mishmash you say?  Read on fearless coder, read on.

Terminology

First, let’s at least agree to some nomenclature.  Failing that, here is MY understanding of MY use of these terms.

View – An unintelligent skin hosting UI controls and bindings and minimal code to call Commands and raise Events.  Can be injected into the View Model at run time.

View Model – All the intelligence behind the View is stored here.  This client side class defines and executes Commands and knows how to respond to events and manipulate UI controls and fields.  This class will pass on all persistence methods to the repository class.  The ViewModel holds a reference to an instance of the client side business object and wraps its properties in ViewModel properties for binding to the UI.  The UI does not bind directly to the business object, but to the ViewModel property instead.  For example, suppose you can’t save a customer until the Name, Phone and City are populated.  The ViewModel owns the state of the Save button (enabled/disabled) and the validation flags for required fields.  It makes sense to put a function in each property setter in the ViewModel for Name, Phone and City that will check whether to enable/disable save.

Repository – A class that knows how to interact with your Data Layer and is responsible for dealing with the persistence methods provided in your ORM framework.  (For example, DevForce has an EntityManager that has a Save method.  The Repository is the only class that should ever call that Save method.)

Business Object – In DevForce 3.5, there’s a client side Silverlight business class that is the synonym of the server-side data class.

Data Object – In DevForce 3.5, the server-side C# version of the business object.  These classes are generated by DevForce from the EntityFramework model.

RowViewModel Conceptual Overview

So here’s the application model for a UI Module with an editable grid.  As an example, let’s imagine we want to provide an editable heirarchical grid with a list of customers in it and a list of their addresses nested underneath each customer row.

First, we need the View and ViewModel for the grid form.

  1.  One View class for the page/tab/control that hosts the grid (e.g. CustomerGridView).

  2.  One ViewModel class backing the page/tab/control that hosts the grid (e.g. CustomerGridViewModel).

The gridView and gridViewModel are responsible for managing interactions around the grid and for actions that affect multiple rows.  For example, "Select All", "Print All", "Expand All", "Print Selected Customers", Filters of all sorts, column sorting, etc.

Second, we need: 

  3.  A RowViewModel class for each row type (e.g. CustomerRowViewModel, AddressRowViewModel).

The gridViewModel holds a collection of the top level <parent>RowViewModels (e.g. CustomerRowViewModels).  Each top level RowViewModel holds a collection of <child>RowViewModels (e.g. AddressRowViewModels).

Lastly, there should be:

  4.  One Repository class to support the functionality represented by the entire page.  This repository is likely inherited from a utility class that provides all the standard repository behavior (persistence, querying, etc.) using generics.

Now that you have been introduced to these classes, here’s how they come together:

Say we have Customers and Addresses.
The Grid itself will be configured as a hierarchical grid with one parent band and one child band.  Where the parent shows each Customer as a row and each Address as a row underneath the Customer row.  Traditionally, you would bind the parent row source to the Customers collection property of the gridViewModel, and the child row source to the Addresses property of the Customer object.

Now, imagine the user starts to edit a cell.  Which cell?  Well, the grid will tell you which cell.  It’s the Customer Rep column for Row 17.  Which customer is bound to Row 17?  Some grids won’t tell you, so you have to jump through hoops to figure it out.  And heaven forbid the grid is sortable because with one click, all your mappings are out of date.  Meanwhile, back to the Customer Rep column.  It’s bound to a combo box.  You have three types of customers:  Volume, Retail, and Educator.  There are different Reps for each type.  Uh-oh.  Now you need, not just any combo box, but a filtered combo that is dependent on the Customer Type (which we’ll assume was selected earlier in the row). 

If you use the Grid’s built-in combo box column type, it is bound to a collection of Customer Reps in the gridViewModel and you can watch as you filter that list and the grid blanks all the rows that have a value that is not in the filtered list.  Yeuch. 

Or you can try a hovering combo that comes to the exact co-ordinates of the cell and hovers above it providing the illusion that it is part of the grid, then you can populate it however you want.  But wait, that means you now have to write all the code to get that combo to work, manage the binding to the instance you need, and get the whole thing to sync properly when you’re done editing it.  Ack!  Oh, and you can’t use the grid’s built-in undo feature any more.

What to do?  Enter the RowViewModel.

Here’s how we bring the RowViewModel into this.

In the parent band, each grid row is a single View for a single RowViewmodel in the gridViewModel.CustomerRowViewModels collection.
Each CustomerRowViewModel holds a collection of its own AddressRowViewModels. 
The child bands (there is one child band for each parent band that has children), have rows, each row in a child band is a View for an AddressRowViewModel.

In this structure, the rows can be bound appropriately and each RowViewModel is responsible for the interactions with 1 and only 1 row in the grid.

Back to our Customer Rep combo box problem.  Now, the CustomerReps collection is a property of the CustomerRowViewModel and the grid’s built-in combobox can be happily bound to the CustomerRowViewModel.CustomerReps collection without complaint.  When the Customer Type changes, the CustomerReps collection is repopulated and the binding will update the combo box automagically.  Yay. No code to translate from Cell to Customer and the tie-in from the CustomerGrid Column binding to the CustomerRowViewModel property is a very standard binding.

So how does this look in code?  I’m going to have to get back to you on that as I put together the code example for this simple scenario.