Mini Kabibi Habibi

Current Path : C:/Users/Public/Documents/DXperience 13.1 Demos/WPF/CS/DockingDemo.Wpf/MVVM/
Upload File :
Current File : C:/Users/Public/Documents/DXperience 13.1 Demos/WPF/CS/DockingDemo.Wpf/MVVM/ViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.ComponentModel;
using System.Diagnostics;
using DevExpress.Xpf.Docking;
using System.Windows.Input;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Win32;
using System.IO;
using System.Windows.Controls;

namespace DockingDemo.MVVM {
    public class RelayCommand : ICommand {
        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;
        public RelayCommand(Action<object> execute)
            : this(execute, null) {
        }
        public RelayCommand(Action<object> execute, Predicate<object> canExecute) {
            if(execute == null)
                throw new ArgumentNullException("execute");
            _execute = execute;
            _canExecute = canExecute;
        }
        #region ICommand Members
        [DebuggerStepThrough]
        public bool CanExecute(object parameter) {
            return _canExecute == null ? true : _canExecute(parameter);
        }
        public event EventHandler CanExecuteChanged {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
        public void Execute(object parameter) {
            _execute(parameter);
        }
        #endregion // ICommand Members
    }
    public abstract class ViewModelBase : DependencyObject, IDisposable {
        protected ViewModelBase() {
        }
        public virtual string DisplayName { get; protected set; }
        public virtual ImageSource Glyph { get; set; }
        #region IDisposable Members
        public void Dispose() {
            this.OnDispose();
        }
        protected virtual void OnDispose() {
        }

#if DEBUG
        /// <summary>
        /// Useful for ensuring that ViewModel objects are properly garbage collected.
        /// </summary>
        ~ViewModelBase() {
            string msg = string.Format("{0} ({1}) ({2}) Finalized", this.GetType().Name, this.DisplayName, this.GetHashCode());
            System.Diagnostics.Debug.WriteLine(msg);
        }
#endif

        #endregion //_ IDisposable Members
    }
    public abstract class WorkspaceViewModel : ViewModelBase {
        #region static
        public static readonly DependencyProperty IsClosedProperty;
        public static readonly DependencyProperty IsOpenedProperty;
        public static readonly DependencyProperty IsActiveProperty;
        static WorkspaceViewModel() {
            IsClosedProperty = DependencyProperty.Register("IsClosed", typeof(bool), typeof(WorkspaceViewModel),
                new PropertyMetadata(true, OnIsClosedChanged));
            IsOpenedProperty = DependencyProperty.Register("IsOpened", typeof(bool?), typeof(WorkspaceViewModel),
                new PropertyMetadata(false));
            IsActiveProperty = DependencyProperty.Register("IsActive", typeof(bool), typeof(WorkspaceViewModel), null);
        }
        static void OnIsClosedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
            WorkspaceViewModel model = (WorkspaceViewModel)d;
            model.OnIsClosedChanged((bool)e.NewValue);
        }
        #endregion
        protected WorkspaceViewModel() {
        }
        public bool IsClosed {
            get { return (bool)GetValue(IsClosedProperty); }
            set { SetValue(IsClosedProperty, value); }
        }
        public bool? IsOpened {
            get { return (bool?)GetValue(IsOpenedProperty); }
            set { SetValue(IsOpenedProperty, value); }
        }
        public bool IsActive {
            get { return (bool)GetValue(IsActiveProperty); }
            set { SetValue(IsActiveProperty, value); }
        }
        RelayCommand _closeCommand;
        public ICommand CloseCommand {
            get {
                if(_closeCommand == null)
                    _closeCommand = new RelayCommand(new Action<object>(OnRequestClose));
                return _closeCommand;
            }
        }
        public event EventHandler RequestClose;
        void OnRequestClose(object param) {
            EventHandler handler = this.RequestClose;
            if(handler != null)
                handler(this, EventArgs.Empty);
        }
        protected virtual void OnIsClosedChanged(bool newValue) {
            IsOpened = !newValue;
        }
    }
    public class CommandViewModel : ViewModelBase {
        public CommandViewModel(string displayName, ICommand command, List<CommandViewModel> commands = null) {
            DisplayName = displayName;
            Command = command;
            if(commands != null)
                Commands = commands;
            IsEnabled = true;
        }
        public ICommand Command { get; private set; }
        public List<CommandViewModel> Commands { get; set; }
        public WorkspaceViewModel Owner { get; set; }
        public bool IsEnabled { get; set; }
        public bool IsSubItem { get; set; }
        public bool IsSeparator { get; set; }
        public KeyGesture KeyGesture { get; set; }
    }
    abstract public class PanelWorkspaceViewModel : WorkspaceViewModel {
        abstract protected string TargetName { get; }
        public PanelWorkspaceViewModel() {
            MVVMHelper.SetTargetName(this, TargetName);
        }
    }
    public class ToolboxViewModel : PanelWorkspaceViewModel {
        protected override string TargetName { get { return "Toolbox"; } }
        public ToolboxViewModel() {
            DisplayName = "Toolbox";
            Glyph = new BitmapImage(new Uri("/DockingDemo;component/Images/VS2010Docking/Toolbox_16x16.png", UriKind.Relative));
        }
    }
    public class SolutionExplorerViewModel : PanelWorkspaceViewModel {
        protected override string TargetName { get { return "RightHost"; } }
        public SolutionExplorerViewModel() {
            DisplayName = "Solution Explorer";
            Glyph = new BitmapImage(new Uri("/DockingDemo;component/Images/VS2010Docking/Solution Explorer.png", UriKind.Relative));
        }
    }
    public class PropertiesViewModel : PanelWorkspaceViewModel {
        protected override string TargetName { get { return "RightHost"; } }
        public PropertiesViewModel() {
            DisplayName = "Properties";
            Glyph = new BitmapImage(new Uri("/DockingDemo;component/Images/VS2010Docking/PropertiesWindow_16x16.png", UriKind.Relative));
        }
    }
    public class ErrorListViewModel : PanelWorkspaceViewModel {
        protected override string TargetName { get { return "BottomHost"; } }
        public ErrorListViewModel() {
            DisplayName = "Error List";
            Glyph = new BitmapImage(new Uri("/DockingDemo;component/Images/VS2010Docking/TaskList_16x16.png", UriKind.Relative));
        }
    }
    public class SearchResultsViewModel : PanelWorkspaceViewModel {
        protected override string TargetName { get { return "BottomHost"; } }
        public SearchResultsViewModel() {
            DisplayName = "Search Results";
            Glyph = new BitmapImage(new Uri("/DockingDemo;component/Images/VS2010Docking/FindInFiles_16x16.png", UriKind.Relative));
        }
    }
    public class OutputViewModel : PanelWorkspaceViewModel {
        protected override string TargetName { get { return "BottomHost"; } }
        public OutputViewModel() {
            DisplayName = "Output";
            Glyph = new BitmapImage(new Uri("/DockingDemo;component/Images/VS2010Docking/Output_16x16.png", UriKind.Relative));
        }
    }
    public class DocumentViewModel : PanelWorkspaceViewModel {
        protected override string TargetName { get { return "DocumentHost"; } }
        public DocumentViewModel(string displayName) {
            DisplayName = displayName;
        }
        public DocumentViewModel() {
        }
        public virtual bool Open() {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            bool? userClickedOK = openFileDialog1.ShowDialog();
            if(userClickedOK == true) {
                DisplayName = openFileDialog1.SafeFileName;
                System.IO.Stream fileStream = File.OpenRead(openFileDialog1.FileName);
                using(System.IO.StreamReader reader = new System.IO.StreamReader(fileStream)) {
                    Text = reader.ReadToEnd();
                }
                fileStream.Close();
            }
            return userClickedOK == true;
        }
        public string Text { get; protected set; }
        public string Footer { get; protected set; }
        public string Description { get; protected set; }
    }
    public class BarModel : ViewModelBase {
        public static readonly DependencyProperty CommandsProperty;
        static BarModel() {
            CommandsProperty = DependencyProperty.Register("Commands", typeof(ObservableCollection<object>), typeof(BarModel), new PropertyMetadata(null));
        }
        public BarModel(string displayName)
            : this() {
                DisplayName = displayName;
        }
        public BarModel() {
            Commands = new ObservableCollection<object>();
        }
        public ObservableCollection<object> Commands {
            get { return ((ObservableCollection<object>)GetValue(CommandsProperty)); }
            set { SetValue(CommandsProperty, value); }
        }
        public bool IsMainMenu { get; set; }
    }

    public class MainWindowViewModel : WorkspaceViewModel {
        ReadOnlyCollection<CommandViewModel> _commands;
        ObservableCollection<WorkspaceViewModel> _workspaces;
        public MainWindowViewModel() {
            DisplayName = "MainWindowViewModel";
            InitDefaultLayout();
        }
        protected virtual void InitDefaultLayout() {
            OpenOrCloseWorkspace(_ToolboxViewModel);
            OpenOrCloseWorkspace(_SolutionExplorerViewModel);
            OpenOrCloseWorkspace(_PropertiesViewModel);
            OpenOrCloseWorkspace(_ErrorListViewModel);
            OpenOrCloseWorkspace(new DocumentViewModel("Document1"), true);
        }
        public ReadOnlyCollection<CommandViewModel> Commands {
            get {
                if(_commands == null) {
                    List<CommandViewModel> cmds = this.CreateCommands();
                    _commands = new ReadOnlyCollection<CommandViewModel>(cmds);
                }
                return _commands;
            }
        }
        protected virtual List<CommandViewModel> CreateViewCommands() {
            CommandViewModel toolbox = new CommandViewModel("Toolbox", new RelayCommand(new Action<object>(OnShowToolboxPanel))) { Glyph = GlyphHelper.GetGlyph("/Images/VS2010Docking/Toolbox_16x16.png"), Owner = _ToolboxViewModel };
            CommandViewModel solutionExplorer = new CommandViewModel("Solution Explorer", new RelayCommand(new Action<object>(OnShowSolutionExplorerPanel))) { Glyph = GlyphHelper.GetGlyph("/Images/VS2010Docking/Solution Explorer.png"), Owner = _SolutionExplorerViewModel };
            CommandViewModel properties = new CommandViewModel("Properties", new RelayCommand(new Action<object>(OnShowPropertiesPanel))) { Glyph = GlyphHelper.GetGlyph("/Images/VS2010Docking/PropertiesWindow_16x16.png"), Owner = _PropertiesViewModel };
            CommandViewModel errorList = new CommandViewModel("Error List", new RelayCommand(new Action<object>(OnShowErrorListPanel))) { Glyph = GlyphHelper.GetGlyph("/Images/VS2010Docking/TaskList_16x16.png"), Owner = _ErrorListViewModel };
            CommandViewModel output = new CommandViewModel("Output", new RelayCommand(new Action<object>(OnShowOutputPanel))) { Glyph = GlyphHelper.GetGlyph("/Images/VS2010Docking/Output_16x16.png"), Owner = _OutputViewModel };
            CommandViewModel searchResults = new CommandViewModel("Search Results", new RelayCommand(new Action<object>(OnShowSearchResultsPanel))) { Glyph = GlyphHelper.GetGlyph("/Images/VS2010Docking/FindInFiles_16x16.png"), Owner = _SearchResultsViewModel };
            return new List<CommandViewModel>() { toolbox, solutionExplorer, properties, errorList, output, searchResults };
        }
        protected virtual List<CommandViewModel> CreateFileCommands() {
            CommandViewModel openDocument = new CommandViewModel("Open...", new RelayCommand(new Action<object>(OnOpenDocument))) { Glyph = GlyphHelper.GetGlyph("/Images/Open_16x16.png"), IsEnabled = true };
            return new List<CommandViewModel>() { openDocument };
        }
        List<CommandViewModel> CreateCommands() {
            List<CommandViewModel> fileCommands = CreateFileCommands();
            List<CommandViewModel> viewCommands = CreateViewCommands();
            var file = new CommandViewModel("File", null, fileCommands);
            var view = new CommandViewModel("View", null, viewCommands);
            return new List<CommandViewModel> { file, view };
        }
        ReadOnlyCollection<BarModel> _bars;
        public ReadOnlyCollection<BarModel> Bars {
            get {
                if(_bars == null) {
                    List<BarModel> cmds = CreateBars();
                    _bars = new ReadOnlyCollection<BarModel>(cmds);
                }
                return _bars;
            }
        }
        protected virtual List<BarModel> CreateBars() {
            BarModel model = new BarModel("Main") { IsMainMenu = true };
            var commands = CreateCommands();
            foreach(var cmd in commands) {
                model.Commands.Add(cmd);
            }
            return new List<BarModel>() { model };
        }

        public ObservableCollection<WorkspaceViewModel> Workspaces {
            get {
                if(_workspaces == null) {
                    _workspaces = new ObservableCollection<WorkspaceViewModel>();
                    _workspaces.CollectionChanged += this.OnWorkspacesChanged;
                }
                return _workspaces;
            }
        }

        void OnWorkspacesChanged(object sender, NotifyCollectionChangedEventArgs e) {
            if(e.NewItems != null && e.NewItems.Count != 0)
                foreach(WorkspaceViewModel workspace in e.NewItems)
                    workspace.RequestClose += this.OnWorkspaceRequestClose;

            if(e.OldItems != null && e.OldItems.Count != 0)
                foreach(WorkspaceViewModel workspace in e.OldItems)
                    workspace.RequestClose -= this.OnWorkspaceRequestClose;
        }

        void OnWorkspaceRequestClose(object sender, EventArgs e) {
            WorkspaceViewModel workspace = sender as WorkspaceViewModel;
            if(workspace is PanelWorkspaceViewModel) {
                ((PanelWorkspaceViewModel)workspace).IsClosed = true;
                if(workspace is DocumentViewModel) {
                    workspace.Dispose();
                    this.Workspaces.Remove(workspace);
                }
            }
        }

        ToolboxViewModel toolBoxViewModel;
        public ToolboxViewModel _ToolboxViewModel {
            get {
                if(toolBoxViewModel == null)
                    toolBoxViewModel = new ToolboxViewModel();
                return toolBoxViewModel;
            }
            set {
                if(toolBoxViewModel == value) return;
                toolBoxViewModel = value;
            }
        }
        SolutionExplorerViewModel solutionExplorerViewModel;
        public SolutionExplorerViewModel _SolutionExplorerViewModel {
            get {
                if(solutionExplorerViewModel == null)
                    solutionExplorerViewModel = new SolutionExplorerViewModel();
                return solutionExplorerViewModel;
            }
            set {
                if(solutionExplorerViewModel == value) return;
                solutionExplorerViewModel = value;
            }
        }
        PropertiesViewModel propertiesViewModel;
        public PropertiesViewModel _PropertiesViewModel {
            get {
                if(propertiesViewModel == null)
                    propertiesViewModel = new PropertiesViewModel();
                return propertiesViewModel;
            }
            set {
                if(propertiesViewModel == value) return;
                propertiesViewModel = value;
            }
        }
        ErrorListViewModel errorListViewModel;
        public ErrorListViewModel _ErrorListViewModel {
            get {
                if(errorListViewModel == null)
                    errorListViewModel = new ErrorListViewModel();
                return errorListViewModel;
            }
            set {
                if(errorListViewModel == value) return;
                errorListViewModel = value;
            }
        }
        OutputViewModel outputViewModel;
        public OutputViewModel _OutputViewModel {
            get {
                if(outputViewModel == null)
                    outputViewModel = new OutputViewModel();
                return outputViewModel;
            }
            set {
                if(outputViewModel == value) return;
                outputViewModel = value;
            }
        }
        SearchResultsViewModel searchResultsViewModel;
        public SearchResultsViewModel _SearchResultsViewModel {
            get {
                if(searchResultsViewModel == null)
                    searchResultsViewModel = new SearchResultsViewModel();
                return searchResultsViewModel;
            }
            set {
                if(searchResultsViewModel == value) return;
                searchResultsViewModel = value;
            }
        }
        protected void OpenOrCloseWorkspace(PanelWorkspaceViewModel workspace, bool activateOnOpen) {
            if(Workspaces.Contains(workspace)) {
                workspace.IsClosed = !workspace.IsClosed;
            }
            else {
                this.Workspaces.Add(workspace);
                workspace.IsClosed = false;
                if(activateOnOpen)
                    this.SetActiveWorkspace(workspace);
            }
        }
        protected void OpenOrCloseWorkspace(PanelWorkspaceViewModel workspace) {
            OpenOrCloseWorkspace(workspace, false);
        }
        void OnShowToolboxPanel(object param) {
            OpenOrCloseWorkspace(_ToolboxViewModel);
        }
        void OnShowSolutionExplorerPanel(object param) {
            OpenOrCloseWorkspace(_SolutionExplorerViewModel);
        }
        void OnShowPropertiesPanel(object param) {
            OpenOrCloseWorkspace(_PropertiesViewModel);
        }
        void OnShowErrorListPanel(object param) {
            OpenOrCloseWorkspace(_ErrorListViewModel);
        }
        void OnShowOutputPanel(object param) {
            OpenOrCloseWorkspace(_OutputViewModel);
        }
        void OnShowSearchResultsPanel(object param) {
            OpenOrCloseWorkspace(_SearchResultsViewModel);
        }
        protected virtual DocumentViewModel GetDocumentViewModel() {
            return new DocumentViewModel();
        }
        void OnOpenDocument(object param) {
            var workspace = GetDocumentViewModel();
            if(!workspace.Open()) return;
            OpenOrCloseWorkspace(workspace, true);
        }

        void SetActiveWorkspace(WorkspaceViewModel workspace) {
            Debug.Assert(this.Workspaces.Contains(workspace));
            workspace.IsActive = true;
        }
        protected static class GlyphHelper {
            public static BitmapImage GetGlyph(string path) {
                return new BitmapImage(DevExpress.Utils.AssemblyHelper.GetResourceUri(typeof(GlyphHelper).Assembly, path));
            }
        }
    }
}