Click here to Skip to main content
15,894,405 members
Articles / Programming Languages / C#

Migrate from Basic to MVVM and MEF Composable Patterns for a Silverlight Application - Part 3

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
3 May 2012CPOL12 min read 24.8K   464   9  
The article series shows how to upgrade a Silverlight application having basic patterns to the MVVM and MEF composable patterns with easy approaches and detailed coding explanations.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using ProductRiaLib.Web.Services;
using ProductRiaLib.Web.Models;
using System.ComponentModel.Composition;
using ProductApp.Common;

namespace ProductApp.Views
{
    [Export(typeof(IModule)), ExportMetadata(MetadataKeys.Name, ModuleID.ProductListView)]
    public partial class ProductList : UserControl, IModule
    {
        AddProductWindow addProductWindow;
        ProductDomainContext ctx;
        Category comboDefault = new Category{ CategoryID = -1, CategoryName = "Please Select" };
        private bool rowEdited = false;

        public ProductList()
        {
            InitializeComponent();
            
            ctx = new ProductDomainContext();            
            ctx.Load(ctx.GetCategoriesQuery()); 
            ctx.Categories.Add(comboDefault);
            categoryCombo.ItemsSource = ctx.Categories;
            categoryCombo.DisplayMemberPath = "CategoryName";
            categoryCombo.SelectedValuePath = "CategoryID";
            categoryCombo.SelectedIndex = 0;            

            addButton.IsEnabled = false;
            saveButton.IsEnabled = false;
            deleteButton.IsEnabled = false;
        }

        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            List<string> categories = new List<string>();
            
            foreach (var category in ctx.Categories)
            {
                if (category.CategoryID == -1) category.CategoryName = "";
                categories.Add(category.CategoryName);
            }            
            addProductWindow = new AddProductWindow(categories);
            addProductWindow.categoryList.SelectedIndex = categoryCombo.SelectedIndex;            
            addProductWindow.Show();
            addProductWindow.AddEvent += new System.EventHandler(addProductWindow_AddEvent);
        }

        void addProductWindow_AddEvent(object sender, System.EventArgs e)
        {
            AddProductWindow addProductWindow = sender as AddProductWindow;
            Category cat = ctx.Categories.Where(c => c.CategoryName == addProductWindow.SelectedCategory).FirstOrDefault();
            Product p = new Product { ProductName = addProductWindow.ProductName, UnitPrice = addProductWindow.Price, Category = cat };
            ctx.Products.Add(p);
            dataGrid1.SelectedItem = p;
            
            if (this.categoryCombo.Items[0].Equals(comboDefault)) ctx.Categories.Remove(comboDefault);
            ctx.SubmitChanges();
            MessageBox.Show("The product has been added.");            
        }

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid1.SelectedItem != null)
            {
                // Cannot use ctx.HasChanges checker duo to added "Please select" item.
                if (rowEdited)
                {
                    if (this.categoryCombo.Items[0].Equals(comboDefault)) ctx.Categories.Remove(comboDefault);
                    ctx.SubmitChanges();
                    MessageBox.Show("The change has been saved.");                   
                }
            }            
        }

        private void deleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (dataGrid1.SelectedItem != null)
            {
                MessageBoxResult result = MessageBox.Show("Do you really want to delete the product?", "Delete Confirmation", MessageBoxButton.OKCancel);
                if (result == MessageBoxResult.OK)
                {
                    Product deletedProduct = dataGrid1.SelectedItem as Product;
                    ctx.Products.Remove(deletedProduct);
                    
                    //if (this.categoryCombo.Items[0].Equals(comboDefault)) ctx.Categories.Remove(comboDefault);
                    ctx.SubmitChanges();
                    MessageBox.Show("The product has been deleted.");
                }
            }            
        }

        private void categoryCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ctx.Products.Clear();            
            
            // Reload the data to context based on the selected category
            Category item = (Category)categoryCombo.SelectedItem;
            if (item != null && item.CategoryID > 0)
            {
                ctx.Load(ctx.GetCategorizedProductQuery((int)item.CategoryID)); 
            }
          
            // Rebind the data to DataGrid
            dataGrid1.ItemsSource = ctx.Products;           
            
            addButton.IsEnabled = true;
            saveButton.IsEnabled = false;
            deleteButton.IsEnabled = false;
        }

        private void dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            saveButton.IsEnabled = true;
            deleteButton.IsEnabled = true;            
        }

        private void dataGrid1_RowEditEnded(object sender, DataGridRowEditEndedEventArgs e)
        {
            rowEdited = true;            
        }   
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Shenwei is a software developer and architect, and has been working on business applications using Microsoft and Oracle technologies since 1996. He obtained Microsoft Certified Systems Engineer (MCSE) in 1998 and Microsoft Certified Solution Developer (MCSD) in 1999. He has experience in ASP.NET, C#, Visual Basic, Windows and Web Services, Silverlight, WPF, JavaScript/AJAX, HTML, SQL Server, and Oracle.

Comments and Discussions