Labels

Monday, September 6, 2010

MVVM - Silverlight Implementation

Implementation:

Before Implmentation, please read the MVVM overview - Link









Model

namespace Arun.Manglick.Silverlight.Model
{
    public class Product : INotifyPropertyChanged
    {
        #region Private Variables

        private int productId;       
        private string modelNumber;
        private string modelName;
        private double unitCost;
        private string description;

        #endregion

        #region Constructor

        public Product()
        {
        }

        public Product(string modelNumber, string modelName,double unitCost, string description)
        {
            ModelNumber = modelNumber;
            ModelName = modelName;
            UnitCost = unitCost;
            Description = description;
        }

        #endregion

        #region Properties

        public int ProductId
        {
            get { return productId; }
            set
            {
                if (value < 0)
                {
                    throw new ArgumentException("Product Id - Can't be less than 0.");
                }
                else
                {
                    productId = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("ProductId"));
                }
            }
        }       
        public string ModelNumber
        {
            get { return modelNumber; }
            set {
                modelNumber = value;
                OnPropertyChanged(new PropertyChangedEventArgs("ModelNumber"));
            }
        }
        public string ModelName
        {
            get { return modelName; }
            set {
                modelName = value;
            OnPropertyChanged(new PropertyChangedEventArgs("ModelName"));
            }
        }
        public double UnitCost
        {
            get { return unitCost; }
            set
            {
                if (value < 0)
                {
                    throw new ArgumentException("Can't be less than 0.");
                }
                else
                {
                    unitCost = value;
                    OnPropertyChanged(new PropertyChangedEventArgs("UnitCost"));
                }
            }
        }
        public string Description
        {
            get { return description; }
            set {
                description = value;
                OnPropertyChanged(new PropertyChangedEventArgs("Description"));
            }
        }

        #endregion

        #region INotifyPropertyChanged Members

        ///
        ///
        ///
        public event PropertyChangedEventHandler PropertyChanged;

        ///
        ///
        ///
        ///






        public void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, e);
        }

        #endregion
    }
}






ViewModel

namespace Arun.Manglick.Silverlight.ViewModels
{
    public class ProductViewModel : INotifyPropertyChanged
    {
        #region Variables

        Product theProduct;
        ObservableCollection<Product> theProducts = new ObservableCollection<Product>();
        public event EventHandler LoadComplete;

        #endregion
       
        #region .ctor
        public ProductViewModel()
        {
        }
        #endregion

        #region Properties

        public ObservableCollection<Product> AllProducts
        {
            get
            {
                return theProducts;
            }
            set
            {
                theProducts = value;
                this.NotifyPropertyChanged("AllProducts");
            }
        }

        public Product SingleProduct
        {
            get
            {
                if (theProducts.Count > 0)
                    return theProducts[0] as Product;

                return null;
            }
            set
            {
                theProduct = value;
                this.NotifyPropertyChanged("SingleProduct");
            }
        }

        #endregion

        #region Methods

        public void Refresh()
        {
            ObservableCollection<Product> lst = GetData();
            AllProducts = lst;
            SingleProduct = theProducts[0] as Product;
            if (LoadComplete != null) LoadComplete(this, null);
        }

        private ObservableCollection<Product> GetData()
        {
            // This could be a Service Call.
            ObservableCollection<Product> lst = new ObservableCollection<Product> {
                new Product{ ProductId=1, ModelNumber="AA", ModelName="AAA", UnitCost=12, Description= "AA DESC"},
                new Product{ ProductId=1, ModelNumber="BB", ModelName="BBB", UnitCost=12, Description= "BB DESC"},
                new Product{ ProductId=1, ModelNumber="CC", ModelName="CCC", UnitCost=12, Description= "CC DESC"}
            };
            return lst;
        }

        #endregion

        #region Property Changed Implementation

        public event PropertyChangedEventHandler PropertyChanged;

        protected void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }

        #endregion
    }
}





View

<navigation:Page x:Class="Arun.Manglick.Silverlight.Views.SimpleBindingProducts"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
                 xmlns:ViewModel="clr-namespace:Arun.Manglick.Silverlight.ViewModels"
                 xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
    <UserControl.Resources>
        <ViewModel:ProductViewModel x:Key="TheProductViewModel"
                                    LoadComplete="viewModel_LoadComplete"
                                    d:IsDataSource="True">ViewModel:ProductViewModel>
    UserControl.Resources>
    <StackPanel>
        <Grid Name="gridProductDetails"
              DataContext="{Binding Path=SingleProduct, Mode=TwoWay, Source={StaticResource TheProductViewModel}}">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto">ColumnDefinition>
                <ColumnDefinition>ColumnDefinition>
            Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto">RowDefinition>
                <RowDefinition Height="Auto">RowDefinition>
                <RowDefinition Height="Auto">RowDefinition>
                <RowDefinition Height="Auto">RowDefinition>
                <RowDefinition Height="Auto">RowDefinition>
                <RowDefinition Height="Auto">RowDefinition>
                <RowDefinition Height="Auto">RowDefinition>
                <RowDefinition Height="Auto">RowDefinition>
            Grid.RowDefinitions>
            <TextBlock Margin="7">Product ID:TextBlock>
            <TextBox Margin="5" Grid.Column="1" x:Name="txtProductId" Text="{Binding ProductId, Mode=TwoWay}">TextBox>
            <TextBlock Margin="7" Grid.Row="1">Model Number:TextBlock>
            <TextBox Margin="5"   Grid.Row="1" Grid.Column="1" Text="{Binding ModelNumber, Mode=OneWay}">TextBox>
            <TextBlock Margin="7" Grid.Row="2">Model Name:TextBlock>
            <TextBox Margin="5"   Grid.Row="2" Grid.Column="1" Text="{Binding ModelName,Mode=TwoWay}">TextBox>
            <TextBlock Margin="7" Grid.Row="3">Unit Cost:TextBlock>
            <TextBox Margin="5" Grid.Row="3" Grid.Column="1" Text="{Binding UnitCost, Mode=TwoWay}">TextBox>
            <TextBlock Margin="7,7,7,0" Grid.Row="4">Description:TextBlock>
            <TextBox Margin="7" Grid.Row="4" Grid.Column="1" Text="{Binding Description , Mode=TwoWay}">TextBox>           
            <StackPanel Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="2" Orientation="Vertical">
                <ProgressBar Height="20" Visibility="Collapsed" IsIndeterminate="True" x:Name="loadingBar" />              
            StackPanel>
        Grid>
        <sdk:DataGrid AutoGenerateColumns="True" Name="dataGrid1"
                      ItemsSource="{Binding Path=AllProducts, Mode=TwoWay, Source={StaticResource TheProductViewModel}}" />
    StackPanel>
navigation:Page>




namespace Arun.Manglick.Silverlight.Views
{
    public partial class SimpleBindingProducts : Page
    {
        ProductViewModel viewModel = null;

        #region Constructor

        public SimpleBindingProducts()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(SimpleBindingProducts_Loaded);
        }

        #endregion

        #region Events





        private void SimpleBindingProducts_Loaded(object sender, RoutedEventArgs e)
        {
            loadingBar.Visibility = Visibility.Visible;
            viewModel = Resources["TheProductViewModel"] as ProductViewModel;
            viewModel.Refresh();
        }





        private void viewModel_LoadComplete(object sender, System.EventArgs e)
        {
            if (loadingBar != null) loadingBar.Visibility = Visibility.Collapsed;
        }

        #endregion
    }
}





Hope this helps.

Thanks & Regards,
Arun Manglick

No comments:

Post a Comment