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.