using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using Microsoft.Win32; namespace Compdfkit_Tools.PDFControl { public partial class FileGridListControl : UserControl, INotifyPropertyChanged { public class FileInfoData { public string FileName { get; set; } public string Size { get; set; } public string Location { get; set; } }; private int _fileNum; public int FileNum { set { _fileNum = value; OnPropertyChanged("FileNum"); OnPropertyChanged("FileNumText"); FileNumChanged?.Invoke(this, EventArgs.Empty); } get => _fileNum; } public string FileNumText => $"Total {FileNum} Files"; public event PropertyChangedEventHandler PropertyChanged; public event EventHandler FileNumChanged; public ObservableCollection FileInfoDataList = new ObservableCollection(); public FileGridListControl() { InitializeComponent(); DataContext = this; FileInfoDataList.CollectionChanged += (sender, args) => { FileNum = FileInfoDataList.Count; }; FileDataGrid.ItemsSource = FileInfoDataList; } private void AddFiles_Click(object sender, RoutedEventArgs e) { var dialog = new OpenFileDialog(); dialog.Multiselect = true; dialog.Filter = @"PDF Files (*.pdf)|*.pdf"; dialog.ShowDialog(); dialog.Multiselect = true; foreach (var fileName in dialog.FileNames) { var file = new FileInfo(fileName); var fileInfoData = new FileInfoData() { FileName = file.Name, Size = GetSizeFromBytes(file.Length), Location = file.FullName }; if (FileInfoDataList.All(item => item.Location != fileInfoData.Location)) { FileInfoDataList.Add(fileInfoData); } } OnPropertyChanged("FileNum"); } private string GetSizeFromBytes(long bytes) { string[] sizes = { "B", "KB", "MB", "GB", "TB" }; double len = bytes; int order = 0; while (len >= 1024 && order < sizes.Length - 1) { order++; len /= 1024; } return $"{len:0.##} {sizes[order]}"; } private void Remove_Click(object sender, RoutedEventArgs e) { if (FileDataGrid.SelectedItems.Count == 0) { FileInfoDataList.Clear(); OnPropertyChanged("FileNum"); return; } var selectedItems = FileDataGrid.SelectedItems; var selectedItemsList = selectedItems.Cast().ToList(); foreach (var item in selectedItemsList) { FileInfoDataList.Remove(item); } OnPropertyChanged("FileNum"); } protected virtual void OnPropertyChanged(string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private void FileDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e) { BtnRemove.Content = FileDataGrid.SelectedItems.Count > 0 ? "Remove" : "Remove All"; } private void FileDataGrid_OnMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if (e.OriginalSource.GetType() != typeof(DataGridCell)) { FileDataGrid.UnselectAll(); } } } }