Click here to Skip to main content
15,897,334 members
Articles / Web Development / ASP.NET

Silverlight RIA Tasks 2: Dynamic View Models

, ,
Rate me:
Please Sign up or sign in to vote.
4.89/5 (25 votes)
18 Jul 2010Ms-PL8 min read 89.6K   3K   55  
Creating multiple dynamic Views using View Model Style and the Silverlight Tab Control.
using System;
using System.Linq;
using System.ComponentModel;
using RIATasks.wsRIATasks;
using System.Collections.ObjectModel;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;

namespace RIATasks
{
    public class TabControlModel : INotifyPropertyChanged
    {
        public TabControlModel()
        {
            AddNewTaskCommand = new DelegateCommand(AddNewTask, CanAddNewTask);
            DeleteTaskCommand = new DelegateCommand(DeleteTask, CanDeleteTask);
            UpdateTaskCommand = new DelegateCommand(UpdateTask, CanUpdateTask);

            // The following line prevents Expression Blend
            // from showing an error when in design mode
            if (!DesignerProperties.IsInDesignTool)
            {
                // Get the Tasks for the current user
                GetTasks();
            }
        }

        #region AddNewTaskCommand
        public ICommand AddNewTaskCommand { get; set; }
        public void AddNewTask(object param)
        {
            SetToNewTask();
        }

        private bool CanAddNewTask(object param)
        {
            // Only allow a New Task to be created
            // If there are no other [New] Tasks

            var colNewTasks = from Tasks in colTabItems
                              where (Tasks.Header as string).Contains("[New]")
                              select Tasks;

            return (colNewTasks.Count() == 0);
        }
        #endregion

        #region DeleteTaskCommand
        public ICommand DeleteTaskCommand { get; set; }
        public void DeleteTask(object param)
        {
            // Get The Task
            Task objTask = GetTaskFromTaskDetails((param as TaskDetails));

            if (objTask.TaskID != -1)
            {
                // Delete Task
                DeleteTask(objTask);
            }
            else
            {
                RemoveTask(objTask.TaskID);
            }
        }

        private bool CanDeleteTask(object param)
        {
            // Only allow this ICommand to fire 
            // if a TaskDetails was passed as a parameter
            return ((param as TaskDetails) != null);
        }
        #endregion

        #region UpdateTaskCommand
        public ICommand UpdateTaskCommand { get; set; }
        public void UpdateTask(object param)
        {
            // Get The Task
            Task objTask = GetTaskFromTaskDetails((param as TaskDetails));

            if (objTask.TaskID == -1)
            {
                // This is a new Task
                InsertTask(objTask);
            }
            else
            {
                // This is an Update
                UpdateTask(objTask);
            }
        }

        private bool CanUpdateTask(object param)
        {
            // Only allow this ICommand to fire 
            // if a TaskDetails was passed as a parameter
            return ((param as TaskDetails) != null);
        }
        #endregion

        // Operations

        #region DeleteTask
        private void DeleteTask(Task objTask)
        {
            // Call the Model to delete the Task
            TasksModel.DeleteTask(objTask.TaskID, (Param, EventArgs) =>
            {
                if (EventArgs.Error == null)
                {
                    // Set the Error Property
                    Message = EventArgs.Result;

                    RemoveTask(objTask.TaskID);
                }
            });
        }
        #endregion

        #region UpdateTask
        private void UpdateTask(Task objTask)
        {
            // Call the Model to UpdateTask the Task
            TasksModel.UpdateTask(objTask, (Param, EventArgs) =>
            {
                if (EventArgs.Error == null)
                {
                    // Set the Error Property
                    Message = EventArgs.Result;
                }
            });
        }
        #endregion

        #region InsertTask
        private void InsertTask(Task objTask)
        {
            // Call the Model to Insert the Task
            TasksModel.InsertTask(objTask, (Param, EventArgs) =>
            {
                if (EventArgs.Error == null)
                {
                    // Set the CurrentTaskID Property
                    // So it can be selected when Tasks re-load
                    CurrentTaskID = EventArgs.Result.TaskID;

                    // Update the Tasks list
                    GetTasks();

                    Message = "";
                }
            });
        }
        #endregion

        #region GetTasks
        private void GetTasks()
        {
            // Clear the current Tasks
            colTabItems.Clear();

            // Call the Model to get the collection of Tasks
            TasksModel.GetTasks((Param, EventArgs) =>
            {
                if (EventArgs.Error == null)
                {
                    // loop thru each item
                    foreach (var objTask in EventArgs.Result)
                    {
                        // Create a TaskItem from the Task
                        TabItem objTabItem = CreateTaskItem(objTask);

                        // Add it to the Collection of TabItems
                        colTabItems.Add(objTabItem);
                    }

                    // Count the records returned
                    if (colTabItems.Count == 0)
                    {
                        // If there are no records, indicate that
                        Message = "No Records Found";
                    }
                    else
                    {
                        Message = "";
                    }

                    // If there is a CurrentTaskID set that 
                    // as the Current task
                    if (CurrentTaskID != -1)
                    {
                        // Locate the Task
                        var objTabItem = (from TaskItem in colTabItems
                                          let VM = (TaskItem.Content as TaskDetails).DataContext
                                          where (VM as TaskDetailsModel).CurrentTask.TaskID == CurrentTaskID
                                          select TaskItem).FirstOrDefault();

                        if (objTabItem != null)
                        {
                            // Set the CurrentTask as selected
                            objTabItem.IsSelected = true;
                        }
                    }
                }
            });
        }
        #endregion

        #region SetToNewTask
        private void SetToNewTask()
        {
            // Unset selected for all Items
            foreach (var item in colTabItems)
            {
                item.IsSelected = false;
            }

            // Create a empty Task
            // so form will be blank
            Task objTask = new Task();

            // Set TaskID = -1 so we know it's a new Task
            objTask.TaskID = -1;

            // Create a TaskItem from the Task
            TabItem objNewTabItem = CreateTaskItem(objTask);

            // Set it as selected
            objNewTabItem.IsSelected = true;

            // Add it to the Collection of TabItems
            this.colTabItems.Add(objNewTabItem);
        }
        #endregion

        #region RemoveTask
        private void RemoveTask(int TaskID)
        {
            // Locate the Task
            var objTabItem = (from TaskItem in colTabItems
                              let VM = (TaskItem.Content as TaskDetails).DataContext
                              where (VM as TaskDetailsModel).CurrentTask.TaskID == TaskID
                              select TaskItem).FirstOrDefault();

            if (objTabItem != null)
            {
                // Remove the Task
                colTabItems.Remove(objTabItem);
            }
        } 
        #endregion

        #region CreateTaskItem
        private TabItem CreateTaskItem(Task Task)
        {
            // Create a Tasks Details
            TaskDetails objTaskDetails = new TaskDetails();
            // Get it's DataContext
            TaskDetailsModel objTaskDetailsModel = (TaskDetailsModel)objTaskDetails.DataContext;
            // Call a method to set the Current Task at it's DataContext
            objTaskDetailsModel.SetCurrentTask(Task);

            // Create a TabItem 
            TabItem objTabItem = new TabItem();
            // Give it a name so it can be prgramatically manipulated
            objTabItem.Name = string.Format("DynamicTab_{0}", Task.TaskID.ToString());
            // Set the Style to point to a Resource that te Designer
            // can later change
            objTabItem.Style = (Style)App.Current.Resources["TabItemStyle1"];
            // Set it's Header
            string strTaskID = (Task.TaskID == -1) ? "[New]" : Task.TaskID.ToString();
            objTabItem.Header = String.Format("Task {0}", strTaskID);
            // Set it's Content to the Tasks Details control
            objTabItem.Content = objTaskDetails;
            return objTabItem;
        }
        #endregion

        #region GetTaskFromTaskDetails
        private Task GetTaskFromTaskDetails(TaskDetails objTaskDetails)
        {
            // Get TaskDetailsModel from 
            TaskDetailsModel objTaskDetailsModel = (TaskDetailsModel)objTaskDetails.DataContext;

            // Get the Task from TaskDetails
            Task objTask = (Task)objTaskDetailsModel.CurrentTask;

            return objTask;
        }
        #endregion

        // Properties

        #region CurrentTaskID
        private int _CurrentTaskID = -1;
        public int CurrentTaskID
        {
            get { return _CurrentTaskID; }
            private set
            {
                if (CurrentTaskID == value)
                {
                    return;
                }
                _CurrentTaskID = value;
                this.NotifyPropertyChanged("CurrentTaskID");
            }
        }
        #endregion

        #region Message
        private string _Message;
        public string Message
        {
            get { return _Message; }
            private set
            {
                if (Message == value)
                {
                    return;
                }
                _Message = value;
                this.NotifyPropertyChanged("Message");
            }
        }
        #endregion

        // Collections

        #region colTabItems
        private ObservableCollection<TabItem> _colTabItems
            = new ObservableCollection<TabItem>();
        public ObservableCollection<TabItem> colTabItems
        {
            get { return _colTabItems; }
            private set
            {
                if (colTabItems == value)
                {
                    return;
                }
                _colTabItems = value;
                this.NotifyPropertyChanged("colTabItems");
            }
        }
        #endregion

        #region INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;

        private void NotifyPropertyChanged(String info)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(info));
            }
        }
        #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 Microsoft Public License (Ms-PL)


Written By
Software Developer (Senior) http://ADefWebserver.com
United States United States
Michael Washington is a Microsoft MVP. He is a ASP.NET and
C# programmer.
He is the founder of
AiHelpWebsite.com,
LightSwitchHelpWebsite.com, and
HoloLensHelpWebsite.com.

He has a son, Zachary and resides in Los Angeles with his wife Valerie.

He is the Author of:

Written By
User Interface Analyst
United Kingdom United Kingdom
I've been playing with computers since my first Acorn Electron, & after blowing up a few ZX Spectrums. I moved on to the C64 & Amiga, & eventually reluctantly on to the PC.

I have learnt a wide set of skills during my 38 years of existence, living in the UK, on the sunny south coast.

My main area of expertise is Graphic/Visual Design, Usability & UI Design. I am not a programmer, but am fairly technically minded due to studying Mechanical Engineering at Uni.

I have work both Freelance & for IBM as a Graphic Designer, & am skilled in the usual graphics packages like, PhotoShop, CorelDraw or Illustrator, Premier, Dreamweaver, Flash etc.
But I originally started with Lightwave & 3D animation.

Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions