C# convert SelectedItemCollection to list, convert System.Windows.Control.ItemCollection to list()

private void ExportSelectedCmdExecuted(object? obj)
{
    //SelectedItemCollection
    var selectedBooksList = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
    ExportListTData<Book>(selectedBooksList);
}

private void ExportAllCmdExecuted(object? obj)
{
    //System.Windows.Control.ItemCollection
    var allItemsList = (((System.Windows.Controls.ItemsControl)obj).Items).OfType<Book>()?.ToList();
    ExportListTData<Book>(allItemsList);
}

 

//All codes

install-package epplus
//xaml
<Window x:Class="WpfApp234.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        WindowState="Maximized"
        xmlns:local="clr-namespace:WpfApp234"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>

        <DataGrid ItemsSource="{Binding BooksList,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  SelectionMode="Extended"
                  SelectedItem="{Binding SelectedBook,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  SelectedIndex="{Binding SelectedIdx,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  AutoGenerateColumns="False">
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <ContextMenu.Items>
                        <MenuItem Header="Export All"
                                  Command="{Binding ExportAllCmd}"
                                  CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget}"/>

                        <MenuItem Header="Export Selected"
                                  Command="{Binding ExportSelectedCmd}"
                                  CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget.SelectedItems}"/>
                    </ContextMenu.Items>
                    
                </ContextMenu>
            </DataGrid.ContextMenu>
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellStyle>
                        <Style TargetType="{x:Type DataGridCell}">
                            <Setter Property="FontSize" Value="50"/>
                            <Setter Property="Height" Value="300"/>
                            <Setter Property="Width" Value="{Binding DataContext.BorderWidth, 
                                RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                                Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                            <Setter Property="BorderBrush" Value="Blue"/>
                            <Setter Property="BorderThickness" Value="2"/>
                            <Style.Triggers>
                                <Trigger Property="IsSelected" Value="True">
                                    <Setter Property="FontSize" Value="80"/>
                                    <Setter Property="Height" Value="600"/>
                                    <Setter Property="BorderBrush" Value="Red"/>
                                    <Setter Property="BorderThickness" Value="5"/>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </DataGridTemplateColumn.CellStyle>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Border BorderBrush="Black" 
                                    BorderThickness="1">
                                <Border.Background>
                                    <ImageBrush ImageSource="{Binding ImgSource}" Stretch="Uniform"/>
                                </Border.Background>
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition/>
                                        <RowDefinition/>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition/>
                                        <ColumnDefinition/>
                                        <ColumnDefinition/>
                                    </Grid.ColumnDefinitions>
                                    <TextBlock Text="{Binding Id}" Grid.Row="0" Grid.Column="0"/>
                                    <TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1"/>
                                    <TextBlock Text="{Binding Title}" Grid.Row="0" Grid.Column="2"/>
                                    <TextBlock Text="{Binding ISBN}" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="3"/>
                                </Grid>
                            </Border>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>



//cs
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using OfficeOpenXml;
using Microsoft.Win32;
using System.Diagnostics.CodeAnalysis;

namespace WpfApp234
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            var vm = new MainVM(this);
            this.DataContext = vm;
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        Window win;
        FrameworkElement fe;
        public MainVM(Window winValue)
        {
            win = winValue;
            if (win != null)
            {
                win.Loaded += Win_Loaded;
                win.SizeChanged += Win_SizeChanged;
            }

        }

        private void Win_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            Init();
        }

        private void Win_Loaded(object sender, RoutedEventArgs e)
        {
            Init();
            InitCommands();
        }

        private void InitCommands()
        {
            ExportAllCmd = new DelCommand(ExportAllCmdExecuted);
            ExportSelectedCmd = new DelCommand(ExportSelectedCmdExecuted);
        }

        private void ExportSelectedCmdExecuted(object? obj)
        {
            //SelectedItemCollection
            var selectedBooksList = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            ExportListTData<Book>(selectedBooksList);
        }

        private void ExportAllCmdExecuted(object? obj)
        {
            //System.Windows.Control.ItemCollection
            var allItemsList = (((System.Windows.Controls.ItemsControl)obj).Items).OfType<Book>()?.ToList();
            ExportListTData<Book>(allItemsList);
        }

        private void ExportListTData<T>(List<T> dataList)
        {
            try
            {
                ExcelPackage.License.SetNonCommercialPersonal("Fred");
                SaveFileDialog dialg = new SaveFileDialog();
                dialg.Filter = "All Files(*.*)|*.*|Excel Files(*.xlsx)|*.xlsx;*.xls";
                dialg.FileName = $"ExcelExport{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString("N")}.xlsx";
                if (dialg.ShowDialog() == true)
                {
                    var fileName = dialg.FileName;
                    var destFile = new FileInfo(fileName);
                    using (var excelPackage = new ExcelPackage(destFile))
                    {
                        var workSheet = excelPackage.Workbook.Worksheets.Add(typeof(T).Name);
                        workSheet.Cells["A1"].LoadFromCollection(dataList, true);
                        excelPackage.Save();
                    }

                    MessageBox.Show($"Export to {fileName}");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public DelCommand ExportAllCmd { get; set; }

        public DelCommand ExportSelectedCmd { get; set; }

        private void Init()
        {
            InitBooksList();
            var tempFe = win.Content as FrameworkElement;
            if (tempFe != null)
            {
                fe = tempFe;
                var tempWidth = win.ActualWidth;
                BorderWidth = fe.ActualWidth;
            }
        }

        private void InitBooksList()
        {
            var dir = @"../../../Images";
            if (Directory.Exists(dir))
            {
                var imgs = Directory.GetFiles(dir);
                int imgsCount = imgs.Count();
                BooksList = new ObservableCollection<Book>();
                for (int i = 0; i < 10000; i++)
                {
                    BooksList.Add(new Book()
                    {
                        Id = i + 1,
                        Name = $"Name_{i + 1}",
                        Title = $"Title_{i + 1}",
                        ISBN = $"ISBN_{Guid.NewGuid().ToString("N")}",
                        ImgSource = GetImageSourceViaUrl(imgs[i % imgsCount])
                    });
                }
            }
        }

        private ImageSource GetImageSourceViaUrl(string imgUrl)
        {
            if (!File.Exists(imgUrl))
            {
                return null;
            }

            BitmapImage bmi = new BitmapImage();
            bmi.BeginInit();
            bmi.UriSource = new Uri(imgUrl, UriKind.RelativeOrAbsolute);
            bmi.EndInit();
            if (bmi.CanFreeze)
            {
                bmi.Freeze();
            }
            return bmi;
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propName = "")
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler?.Invoke(this, new PropertyChangedEventArgs(propName));
            }
        }

        private ObservableCollection<Book> booksList;
        public ObservableCollection<Book> BooksList
        {
            get
            {
                return booksList;
            }
            set
            {
                if (value != booksList)
                {
                    booksList = value;
                    OnPropertyChanged(nameof(BooksList));
                }
            }
        }

        private Book selectedBook;
        public Book SelectedBook
        {
            get
            {
                return selectedBook;
            }
            set
            {
                if (value != selectedBook)
                {
                    selectedBook = value;
                    OnPropertyChanged();
                }
            }
        }

        private int selectedIdx;
        public int SelectedIdx
        {
            get
            {
                return selectedIdx;
            }
            set
            {
                if (value != selectedIdx)
                {
                    selectedIdx = value;
                    OnPropertyChanged();
                }
            }
        }

        private double borderWidth;
        public double BorderWidth
        {
            get
            {
                return borderWidth;
            }
            set
            {
                if (value != borderWidth)
                {
                    borderWidth = value;
                    OnPropertyChanged();
                }
            }
        }
    }


    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string ISBN { get; set; }
        public ImageSource ImgSource { get; set; }
    }

    public class DelCommand : ICommand
    {
        private Action<object?> execute;
        private Predicate<object?> canExecute;
        public DelCommand(Action<object?> executeValue, Predicate<object?> canExecuteValue = null)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        public bool CanExecute(object? parameter)
        {
            return canExecute == null ? true : canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            execute(parameter);
        }
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2025-05-27 00:42  FredGrit  阅读(13)  评论(0)    收藏  举报