WPF SelectedItemCollection convert to IList and List, such as Datagrid SelectedItems

FredGrit發表於2024-10-11
private void ExportSelectedCmdExecuted(object obj)
{
    var items = (System.Collections.IList)obj;
    if (items != null && items.Count > 0)
    {
        var booksList = items.Cast<Book>()?.ToList();
        if (booksList != null && booksList.Any())
        {
            SaveBooksListAsJsonFile(booksList);
        }
    }
}

var items = (System.Collections.IList)obj;
var booksList = items.Cast<Book>()?.ToList();

//xaml
<Window x:Class="WpfApp20.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"
        xmlns:local="clr-namespace:WpfApp20"
        WindowState="Maximized"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:BookVM/>
    </Window.DataContext>
    <Window.Resources>
        <Style TargetType="{x:Type DataGridCell}" x:Key="cellStyle">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type DataGridCell}">
                        <Border x:Name="border"
            BorderBrush="Transparent"
            BorderThickness="1"
            SnapsToDevicePixels="True"
                            Width="200"
                                Height="500">
                            <Border.Background>
                                <ImageBrush ImageSource="{Binding ImgUrl}"/>
                            </Border.Background>
                            <ContentPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="Load" Width="200" FontSize="30" Command="{Binding LoadCmd}"/>
            <Button Content="Clear" Width="200" FontSize="30" Command="{Binding ClearCmd}"/>
            <Button Content="Export Selected" Width="300" FontSize="30" 
                    Command="{Binding ExportSelectedCmd}"
                    CommandParameter="{Binding Path=SelectedItems,ElementName=dg}"/>
        </ToolBar>
        <DataGrid x:Name="dg"
                  Grid.Row="1"
                  ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  SelectionMode="Extended"
                  CanUserAddRows="False"
                  AutoGenerateColumns="False"
                  VirtualizingPanel.CacheLength="1"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  VirtualizingPanel.IsContainerVirtualizable="True"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTemplateColumn Header="Image">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding ImgUrl}"
                                   Width="200"
                                   Height="500"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>                  
    </Grid>
</Window>



//cs
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 Microsoft.Win32;
using Newtonsoft.Json;

namespace WpfApp20
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }


    public class BookVM : INotifyPropertyChanged
    {
        public BookVM()
        {
            InitData();
            InitCommands();
        }

        private void InitCommands()
        {
            LoadCmd = new DelCommand(LoadCmdExecuted);
            ClearCmd = new DelCommand(ClearCmdExecuted);
            ExportSelectedCmd = new DelCommand(ExportSelectedCmdExecuted);
        }

        private void ExportSelectedCmdExecuted(object obj)
        {
            var items = (System.Collections.IList)obj;
            if (items != null && items.Count > 0)
            {
                var booksList = items.Cast<Book>()?.ToList();
                if (booksList != null && booksList.Any())
                {
                    SaveBooksListAsJsonFile(booksList);
                }
            }
        }

        private void SaveBooksListAsJsonFile(List<Book> booksList = null, string jsonFile = "")
        {
            if (booksList == null || !booksList.Any())
            {
                return;
            }

            SaveFileDialog dialog = new SaveFileDialog();
            dialog.Filter = "Json Files|*.json|All Files|*.*";
            dialog.FileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}{Guid.NewGuid().ToString("N")}.json";
            if(dialog.ShowDialog()==true)
            {
                string jsonStr=JsonConvert.SerializeObject(booksList,Formatting.Indented);
                using(StreamWriter jsonWriter=new StreamWriter(dialog.FileName, false, Encoding.UTF8))
                {
                    jsonWriter.WriteLine(jsonStr);
                    MessageBox.Show($"Saved in\b{dialog.FileName}");
                }
            }
        }

        private void ClearCmdExecuted(object obj)
        {
            BooksCollection = new ObservableCollection<Book>();
        }

        private void LoadCmdExecuted(object obj)
        {
            InitData();
        }

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

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

        public DelCommand LoadCmd { get; set; }

        public DelCommand ClearCmd { get; set; }

        public DelCommand ExportSelectedCmd { get; set; }

        private void InitData()
        {
            var imgsList = new List<string>(Directory.GetFiles(@"../../Images"));
            if (imgsList != null && imgsList.Any())
            {
                int imgsCount = imgsList.Count;
                BooksCollection = new ObservableCollection<Book>();
                for (int i = 0; i < 10; i++)
                {
                    var imgBrush = new ImageBrush();
                    BitmapImage bmi = new BitmapImage();
                    bmi.BeginInit();
                    bmi.UriSource=new Uri(imgsList[i%imgsCount],UriKind.RelativeOrAbsolute);
                    bmi.EndInit();
                    if(bmi.CanFreeze)
                    {
                        bmi.Freeze();
                    }
                    imgBrush.ImageSource = bmi;
                    BooksCollection.Add(new Book()
                    {
                        Id = i + 1,
                        Name = $"Name_{i + 1}",
                        ISBN = $"ISBN_{Guid.NewGuid().ToString("N")}",
                        ImgUrl = $"{imgsList[i % imgsCount]}"
                    });
                }
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }

        public string ISBN { get; set; }

        public string Name { get; set; }

        public string ImgUrl { get; set; }
    }

    public class DelCommand : ICommand
    {
        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        private Action<object> execute;
        private Predicate<object> canExecute;

        public DelCommand(Action<object> executeValue, Predicate<object> canExecuteValue = null)
        {
            execute = executeValue;
            canExecute = canExecuteValue;
        }

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

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

相關文章