首页 > 其他分享 >WPF datagrid export command in mvvm and customize delegatecommand inherited from ICommand

WPF datagrid export command in mvvm and customize delegatecommand inherited from ICommand

时间:2024-11-03 17:10:37浏览次数:4  
标签:ICommand delegatecommand mvvm object System private new using public

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);
    }
}

public DelCommand ExportCommand { get; set; }

ExportCommand = new DelCommand(ExportCommandExecuted);

private void ExportCommandExecuted(object obj)
{
    var dg = obj as DataGrid;
    if (dg != null)
    {
        var items = dg.ItemsSource.Cast<Book>()?.ToList();
        if (items != null && items.Any())
        {
            string fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString("N")}.json";
            var msgBoxResult = MessageBox.Show($"Are you sure to export to \n{fileName}?",
                "Export", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);
            if(msgBoxResult == MessageBoxResult.Yes)
            {
                var fStream=File.Create(fileName);
                fStream.SerializeBigCollectionSerializer<Book>(BooksCollection);
                MessageBox.Show($"Export to \n{fileName}", "Export");
            }
        }
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

//xaml
<Window x:Class="WpfApp26.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:behavior="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:local="clr-namespace:WpfApp26"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:BookVM/> 
    </Window.DataContext>
    <Window.Resources>
        <local:SizeConverter x:Key="sizeConverter"/>
        <Style TargetType="{x:Type Button}"  x:Key="btnStyle">
            <Setter Property="Width" Value="200"/>
            <Setter Property="FontSize" Value="30"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToolBar Grid.Row="0">
            <Button Content="Load" Command="{Binding LoadCommand}" 
                    CommandParameter="{Binding ElementName=dg}" Style="{StaticResource btnStyle}"/>
            <Button Content="Clear" Command="{Binding ClearCommand}" 
                    CommandParameter="{Binding ElementName=dg}" Style="{StaticResource btnStyle}"/>
            <Button Content="Export" Command="{Binding ExportCommand}"
                    CommandParameter="{Binding ElementName=dg}" Style="{StaticResource btnStyle}"/>
        </ToolBar>
        <DataGrid Grid.Row="1"
                  x:Name="dg"
                  ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  CanUserAddRows="False"
                  AutoGenerateColumns="False"
                  SelectionMode="Extended">
            <behavior:Interaction.Triggers>
                <behavior:EventTrigger EventName="SelectionChanged">
                    <behavior:CallMethodAction MethodName="DataGrid_SelectionChanged" 
                                               TargetObject="{Binding}"/>
                </behavior:EventTrigger>
            </behavior:Interaction.Triggers>
            <DataGrid.Columns>
                <DataGridTextColumn Header="Id" Binding="{Binding Id}"/>
                <DataGridTextColumn Header="ISBN" Binding="{Binding ISBN}"/>
                <DataGridTemplateColumn Header="Image">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Border 
                                Width="{Binding ActualWidth,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                                Converter={StaticResource sizeConverter}}"
                                Height="{Binding ActualHeight,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Window}},
                                Converter={StaticResource sizeConverter}}">
                                <Border.Background>
                                    <ImageBrush ImageSource="{Binding ImgSource}" Stretch="Uniform" />
                                </Border.Background>
                            </Border>
                        </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.Security.Policy;
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 System.Data.SqlTypes;
using System.Globalization;
using Newtonsoft.Json;

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

    public class BookVM : INotifyPropertyChanged
    {
        private List<string> imgsList { get; set; }
        private int imgsCount = 0;

        public BookVM()
        {
            InitData();
            InitCommands();
        }

        private void InitCommands()
        {
            LoadCommand = new DelCommand(LoadCommandExecuted);
            ClearCommand = new DelCommand(ClearCommandExecuted);
            ExportCommand = new DelCommand(ExportCommandExecuted);
        }

        private void ExportCommandExecuted(object obj)
        {
            var dg = obj as DataGrid;
            if (dg != null)
            {
                var items = dg.ItemsSource.Cast<Book>()?.ToList();
                if (items != null && items.Any())
                {
                    string fileName = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}_{Guid.NewGuid().ToString("N")}.json";
                    var msgBoxResult = MessageBox.Show($"Are you sure to export to \n{fileName}?",
                        "Export", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes);
                    if(msgBoxResult == MessageBoxResult.Yes)
                    {
                        var fStream=File.Create(fileName);
                        fStream.SerializeBigCollectionSerializer<Book>(BooksCollection);
                        MessageBox.Show($"Export to \n{fileName}", "Export");
                    }
                }
            }
        }



        private void ClearCommandExecuted(object obj)
        {
            var dg = obj as DataGrid;
            if (dg != null)
            {
                BooksCollection?.Clear();
            }
        }

        private void LoadCommandExecuted(object obj)
        {
            BooksCollection?.Clear();
            InitData();
        }

        private void InitData()
        {
            var imgs = Directory.GetFiles(@"../../Images");
            if (imgs != null && imgs.Any())
            {
                imgsCount = imgs.Count();
                imgsList = new List<string>(imgs);
                BooksCollection = new ObservableCollection<Book>();
                for (int i = 0; i < 2000000; i++)
                {
                    Book book = new Book()
                    {
                        Id = i + 1,
                        ISBN = $"ISBN_{Guid.NewGuid().ToString("N")}",
                        Name = $"Name_{i + 1}",
                        Topic = $"Topic_{i + 1}",
                        ImgUrl = $"{imgs[i % imgsCount]}",
                        ImgSource = GetImgSource(imgs[i % imgsCount])
                    };
                    BooksCollection.Add(book);
                }
            }
        }

        private ImageSource GetImgSource(string url)
        {
            BitmapImage bmi = new BitmapImage();
            bmi.BeginInit();

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

        public void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var dg = e.OriginalSource as DataGrid;
            if (dg != null)
            {
                var items = dg.SelectedItems?.Cast<Book>().ToList();
                if (items != null && items.Any())
                {
                    MessageBox.Show($"Selected {items.Count()}!\n");
                }
            }
        }

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

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

        public DelCommand LoadCommand { get; set; }
        public DelCommand ClearCommand { get; set; }
        public DelCommand ExportCommand { get; set; }
    }

    public static class BigCollectionStream
    {
        public static void SerializeBigCollectionSerializer<T>(this Stream stream,IEnumerable<T> items)
        {
            using(StreamWriter streamWriter =new StreamWriter(stream))
            {
                var serializer = new JsonSerializer();
                serializer.Formatting = Formatting.Indented;
                serializer.Serialize(streamWriter, items);
            }
        }
    }

    public class SizeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double d = 0;
            if (double.TryParse(value?.ToString(), out d))
            {
                return d / 2;
            }
            return d;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

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

        public string Name { get; set; }

        public string Topic { get; set; }

        public string ImgUrl { get; set; }

        public string ISBN { get; set; }

        public ImageSource ImgSource { 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);
        }
    }


}

 

标签:ICommand,delegatecommand,mvvm,object,System,private,new,using,public
From: https://www.cnblogs.com/Fred1987/p/18523654

相关文章

  • WPF datagrid implement multi select via behavior selectionchanged event in MVVM
    <DataGridItemsSource="{BindingBooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"CanUserAddRows="False"AutoGenerateColumns="False"SelectionMode="Extended">......
  • CommunityToolkit.Mvvm中的Ioc
    什么是Ioc在软件工程中,控制反转(IoC)是一种设计原则,其中计算机程序的自定义编写部分从外部源(例如框架)接收控制流。术语“反转”是历史性的:与过程式编程相比,具有这种设计的软件架构“反转”了控制。在过程式编程中,程序的自定义代码调用可重用库来处理通用任务,但在控制反转的情况下,是......
  • WPF+MVVM案例实战(十二)- 3D数字翻牌计时实现
    文章目录1、运行效果2、功能实现1、文件创建2、控件代码实现3、控件引用与菜单实现1.引用用户控件2.按钮菜单1、运行效果2、功能实现1、文件创建打开项目Wpf_Examples,在用户控件UserControlLib中创建NumberFoldingCard.xaml文件,在主程序......
  • 4、.Net 快速开发框架:WalkingTec.Mvvm - 开源项目研究文章
    WalkingTec.Mvvm框架(简称WTM)是一个基于.NETCore的快速开发框架,它支持Layui(前后端不分离)、React(前后端分离)、Vue(前后端分离)等多种前端UI框架,并内置了代码生成器以提高开发效率。WTM的核心特点包括:多前端UI支持:支持Layui、React、Vue等前端UI框架,满足不同开发需求......
  • WPF+Mvvm案例实战(五)- 自定义雷达图实现
    文章目录1、项目准备1、创建文件2、用户控件库2、功能实现1、用户控件库1、控件样式实现2、数据模型实现2、应用程序代码实现1.UI层代码实现2、数据后台代码实现3、主界面菜单添加1、后台按钮方法改造:2、按钮添加:3、依赖注入3、运行效果4、源代码获取1、项目准......
  • WPF+MVVM案例实战(六)- 自定义分页控件实现
    文章目录1、项目准备2、功能实现1、分页控件DataPager实现2、分页控件数据模型与查询行为3、数据界面实现3、运行效果4、源代码获取1、项目准备打开项目Wpf_Examples,新建PageBarWindow.xaml界面、PageBarViewModel.cs,在用户控件库UserControlLib中创建用......
  • Android MVVM
    AndroidMVVM介绍MVVM(Model-View-ViewModel)是Android开发中常用的一种架构模式。它将应用程序的逻辑分离为三个主要部分:Model(模型)、View(视图)和ViewModel(视图模型),从而使代码更清晰、更易于维护。1.Model(模型)Model代表应用程序的数据和业务逻辑。它负责处理数据的获取、存储和......
  • WebBrowser采用MVVM绑定的方式更新内容
    WebBrowser本身并没有提供MVVM方式更新网页内容的方式。因为现在公司的项目基本上都使用MVVM的方式开发了。所以想着,也可以简单地封装一个类来实现前后台绑定的功能实现代码:publicstaticclassWebBrowserBehaviour{publicstaticreadonlyDependencyPropertyHtmlTex......
  • 轻松上手-MVVM模式_关系型数据库_云函数T云数据库
    作者:狼哥团队:坚果派团队介绍:坚果派由坚果等人创建,团队拥有12个华为HDE带领热爱HarmonyOS/OpenHarmony的开发者,以及若干其他领域的三十余位万粉博主运营。专注于分享HarmonyOS/OpenHarmony、ArkUI-X、元服务、仓颉。团队成员聚集在北京,上海,南京,深圳,广州,宁夏等地,目前已开发鸿蒙原......
  • WPF中MVVM的应用举例
    WPF(WindowsPresentationFoundation)是微软开发的用于创建用户界面的框架,而MVVM(Model-View-ViewModel)模式是一种分离前端UI逻辑与后台业务逻辑的方法。在WPF中使用MVVM模式可以提高代码的可维护性、可测试性和可扩展性。在这篇文章中,我们将深入探讨WPF中的MVVM模式,并通过具......