using System.Collections.ObjectModel; using System.Linq; using System.Windows.Input; namespace WpfTreeView { /// /// A view model for each directory item /// public class DirectoryItemViewModel : BaseViewModel { #region Public Properties /// /// The type of this item /// public DirectoryItemType Type { get; set; } public string ImageName => Type == DirectoryItemType.Drive ? "drive" : (Type == DirectoryItemType.File ? "file" : (IsExpanded ? "folder-open" : "folder-closed")); /// /// The full path to the item /// public string FullPath { get; set; } /// /// The name of this directory item /// public string Name { get { return this.Type == DirectoryItemType.Drive ? this.FullPath : DirectoryStructure.GetFileFolderName(this.FullPath); } } /// /// A list of all children contained inside this item /// public ObservableCollection Children { get; set; } /// /// Indicates if this item can be expanded /// public bool CanExpand { get { return this.Type != DirectoryItemType.File; } } /// /// Indicates if the current item is expanded or not /// public bool IsExpanded { get { return this.Children?.Count(f => f != null) > 0; } set { // If the UI tells us to expand... if (value == true) // Find all children Expand(); // If the UI tells us to close else this.ClearChildren(); } } #endregion #region Public Commands /// /// The command to expand this item /// public ICommand ExpandCommand { get; set; } #endregion #region Constructor /// /// Default constructor /// /// The full path of this item /// The type of item public DirectoryItemViewModel(string fullPath, DirectoryItemType type) { // Create commands this.ExpandCommand = new RelayCommand(Expand); // Set path and type this.FullPath = fullPath; this.Type = type; // Setup the children as needed this.ClearChildren(); } #endregion #region Helper Methods /// /// Removes all children from the list, adding a dummy item to show the expand icon if required /// private void ClearChildren() { // Clear items this.Children = new ObservableCollection(); // Show the expand arrow if we are not a file if (this.Type != DirectoryItemType.File) this.Children.Add(null); } #endregion /// /// Expands this directory and finds all children /// private void Expand() { // We cannot expand a file if (this.Type == DirectoryItemType.File) return; // Find all children var children = DirectoryStructure.GetDirectoryContents(this.FullPath); this.Children = new ObservableCollection( children.Select(content => new DirectoryItemViewModel(content.FullPath, content.Type))); } } }