Click here to Skip to main content
15,894,460 members
Articles / Desktop Programming / WPF

Modeling M-V-VM

Rate me:
Please Sign up or sign in to vote.
3.71/5 (8 votes)
5 Jun 2009CPOL2 min read 26.9K   312   23  
An article which tries to present an approach for decoupling M-V-VM View Model objects
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.ComponentModel;

using WorldDataLib.Model;

namespace TestTreeViewWithRightBarView.ViewModel
{


    public class MainViewModel : IViewModel, INotifyPropertyChanged
    {
        #region Helper Classes

        private delegate void VMEventHandler(IViewModel sender, object param);

        #endregion

        #region Members

        /// <summary>
        /// A dictionary which holds delegates for handling the events
        /// </summary>
        Dictionary<ViewModelOperationsEnum, VMEventHandler> m_EventHandler;
        ObservableCollection<TreeRootViewModel> m_TreeRootViewModel;        

        #endregion

        #region Properties

        public ObservableCollection<TreeRootViewModel> TreeRootViewModel
        {
            get 
            { 
                return m_TreeRootViewModel; 
            }
        }

        /// <summary>
        /// The currently selected Tree node
        /// </summary>
        public ITreeViewNode CurrentNode
        {
            get;
            set;
        }

        #endregion

        #region Methods

        #region Ctor

        public MainViewModel()
        {
            m_EventHandler = new Dictionary<ViewModelOperationsEnum, VMEventHandler>();
            m_TreeRootViewModel = new ObservableCollection<TreeRootViewModel>();            
            InitEventHandlers();
            LoadDataFromFile();
        }

        #endregion

        #region IViewModel Members

        public IViewModel VMParent
        {
            get 
            {
                throw new NotImplementedException(); 
            }
        }

        /// <summary>
        /// Upon a comming event, check if it appears in the hanlder dictionary
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="param"></param>
        /// <param name="viewModelEvent"></param>
        public void HandleEvent(IViewModel sender, object param, ViewModelOperationsEnum viewModelEvent)
        {
            VMEventHandler handler;
            if (m_EventHandler.TryGetValue(viewModelEvent, out handler))
            {
                handler(sender, param);
            }
        }

        #endregion

        #region Event Handlers

        private void InitEventHandlers()
        {
            m_EventHandler.Add(ViewModelOperationsEnum.GotFocus, this.ControlGotFocus);
            m_EventHandler.Add(ViewModelOperationsEnum.GetContinentSize, this.GetContinentSize);
            m_EventHandler.Add(ViewModelOperationsEnum.GetCountryCurrency, this.GetCounrtyCurrency);
            m_EventHandler.Add(ViewModelOperationsEnum.GetCityTemprature, this.GetCityTemprature);
        }

        /// <summary>
        /// When an event of Got Focus appears. The current node should be updated
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="param"></param>
        public void ControlGotFocus(IViewModel sender, object param)
        {
            ITreeViewNode node = sender as ITreeViewNode;
            if (node != null)
            {
                CurrentNode = node;
                OnPropertyChanged("CurrentNode");
            }
        }

        public void GetContinentSize(IViewModel sender, object param)
        {
            using (WorldServiceReference.WorldDataServiceClient client = new TestTreeViewWithRightBarView.WorldServiceReference.WorldDataServiceClient())
            {
                double size = client.GetContinentSizeInSquareMiles(param as string);
                IContinentViewModel vm = sender as IContinentViewModel;
                if (vm != null)
                {
                    vm.SetSize(size);
                }
            }
        }

        public void GetCounrtyCurrency(IViewModel sender, object param)
        {
            using (WorldServiceReference.WorldDataServiceClient client = new TestTreeViewWithRightBarView.WorldServiceReference.WorldDataServiceClient())
            {
                CurrenciesEnum currency = client.GetCountryCurrency(param as string);
                ICountryViewModel vm = sender as ICountryViewModel;
                if (vm != null)
                {
                    vm.SetCurrency(currency);
                }
            }
        }

        public void GetCityTemprature(IViewModel sender, object param)
        {
            using (WorldServiceReference.WorldDataServiceClient client = new TestTreeViewWithRightBarView.WorldServiceReference.WorldDataServiceClient())
            {
                double temprature = client.GetCityCurrentTemprature(param as string);
                ICityViewModel vm = sender as ICityViewModel;
                if (vm != null)
                {
                    vm.SetTemprature(temprature);
                }
            }
        }

        #endregion

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

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

        #endregion

        private void LoadDataFromFile()
        {
            List<Continent> continents = null;

            System.Xml.Serialization.XmlSerializer serialzer = new System.Xml.Serialization.XmlSerializer(typeof(List<Continent>));
            System.IO.Stream stream = null;
            try
            {
                stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("TestTreeViewWithRightBarView.Resources.Continents.xml");
                continents = (List<Continent>)serialzer.Deserialize(stream);
                m_TreeRootViewModel.Add(new TreeRootViewModel(this, continents));
            }
            catch (Exception)
            {
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }
            
        }

        #endregion

        
    }
}

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
Software Developer
Israel Israel
Software Developer in a promising Clean-Tech company

Comments and Discussions