WPF loading data asynchronously and contextmenu save as json in mvvm

news/2025/10/20 22:25:09/文章来源:https://www.cnblogs.com/Fred1987/p/19153827
Install-Package Prism.Wpf;
Install-Package Prism.DryIOC;
Install-Package System.Text.Json;
<prism:PrismApplication x:Class="WpfApp36.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WpfApp36"xmlns:prism="http://prismlibrary.com/"><prism:PrismApplication.Resources></prism:PrismApplication.Resources>
</prism:PrismApplication>
using System.Configuration;
using System.Data;
using System.Windows;namespace WpfApp36
{/// <summary>/// Interaction logic for App.xaml/// </summary>public partial class App : PrismApplication{protected override Window CreateShell(){return Container.Resolve<MainWindow>();}protected override void RegisterTypes(IContainerRegistry containerRegistry){containerRegistry.RegisterSingleton<IIDService, IDService>();containerRegistry.RegisterSingleton<IISBNService,ISBNService>();containerRegistry.RegisterSingleton<INameService, NameService>();containerRegistry.Register<MainWindow>();containerRegistry.Register<MainVM>();}}}
<Window x:Class="WpfApp36.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:WpfApp36"mc:Ignorable="d"WindowState="Maximized"Title="{Binding MainTitle}" Height="450" Width="800"><Grid><DataGrid ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"VirtualizingPanel.IsVirtualizing="True"VirtualizingPanel.CacheLengthUnit="Item"VirtualizingPanel.CacheLength="2,2"VirtualizingPanel.VirtualizationMode="Recycling"ScrollViewer.IsDeferredScrollingEnabled="True"ScrollViewer.CanContentScroll="True"FontSize="30"AutoGenerateColumns="True"CanUserAddRows="False"IsReadOnly="True"><DataGrid.ContextMenu><ContextMenu><MenuItem Header="Save As Json File"Command="{Binding SaveAsJsonFileCommand}"CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},Path=PlacementTarget}"/></ContextMenu></DataGrid.ContextMenu></DataGrid></Grid>
</Window>
using Microsoft.Win32;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;namespace WpfApp36
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(MainVM vm){InitializeComponent();this.DataContext = vm;this.Loaded += async (s, e) =>{await vm.InitBooksCollection();};}}public class MainVM : INotifyPropertyChanged{private IIDService idService;private INameService nameService;private IISBNService isbnService;public MainVM(IIDService idServiceValue, INameService nameServiceValue, IISBNService isbnServiceValue){idService = idServiceValue;nameService = nameServiceValue;isbnService = isbnServiceValue;SaveAsJsonFileCommand = new DelCommand(SaveAsJsonFileCommandExecuted);}private void SaveAsJsonFileCommandExecuted(object? obj){try{SaveFileDialog dialog = new SaveFileDialog();dialog.Filter = "Json File|*.json";dialog.FileName = $"Json_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}";if (dialog.ShowDialog() == true){var dg = obj as DataGrid;var items = dg.Items.Cast<Book>()?.ToList();var jsonStr = JsonSerializer.Serialize(items,new JsonSerializerOptions(){WriteIndented = true});using (StreamWriter writer = new StreamWriter(dialog.FileName, true, Encoding.UTF8)){writer.WriteLine(jsonStr);}MessageBox.Show($"Saved in {dialog.FileName}");}}catch (Exception ex){MessageBox.Show(ex.Message);    }                      }public async Task InitBooksCollection(){BooksCollection = new ObservableCollection<Book>();List<Book> booksList = new List<Book>();for (int i = 1; i < 3000001; i++){booksList.Add(new Book(){Id = idService.GetID(),Name = nameService.GetName(),ISBN = isbnService.GetISBN(),Comment = $"Comment_{i}",Content = $"Content_{i}",Summary = $"Summary_{i}",Title = $"Title_{i}",Topic = $"Topic_{i}"});if (i % 1000000 == 0){var tempList = booksList.ToList();booksList.Clear();await Application.Current.Dispatcher.InvokeAsync(() =>{foreach (var book in tempList){BooksCollection.Add(book);}MainTitle = $"Now is {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}," +$"loaded {BooksCollection.Count} items";}, System.Windows.Threading.DispatcherPriority.Background);}}}public ICommand SaveAsJsonFileCommand { get; set;  }public event PropertyChangedEventHandler? PropertyChanged;private void OnPropertyChanged([CallerMemberName] string propertyName = ""){var handler = PropertyChanged;if (handler != null){handler?.Invoke(this, new PropertyChangedEventArgs(propertyName));}}private string mainTitle;public string MainTitle{get{return mainTitle;}set{if (value != mainTitle){mainTitle = value;OnPropertyChanged();}}}private ObservableCollection<Book> booksCollection;public ObservableCollection<Book> BooksCollection{get{return booksCollection;}set{if (value != booksCollection){booksCollection = value;OnPropertyChanged();}}}}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);}}public interface IIDService{int GetID();}public class IDService : IIDService{int id = 0;public int GetID(){return Interlocked.Increment(ref id);}}public interface INameService{string GetName();}public class NameService : INameService{int idx = 0;public string GetName(){return $"Name_{Interlocked.Increment(ref idx)}";}}public interface IISBNService{string GetISBN();}public class ISBNService : IISBNService{int idx = 0;public string GetISBN(){return $"ISBN_{Interlocked.Increment(ref idx)}_{Guid.NewGuid():N}";}}public class Book{public int Id { get; set; }public string Name { get; set; }public string ISBN { get; set; }public string Comment { get; set; }public string Content { get; set; }public string Summary { get; set; }public string Title { get; set; }public string Topic { get; set; }}
}

 

 

 

image

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/941682.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Android 源码解析系列1- Android init 进程启动流程

Android 源码解析系列1- Android init 进程启动流程Android 源码解析系列1- Android init 进程启动流程 init进程是用户空间的第一个进程.如下 g1930fua_g210_ai:/ $ ps -ef | grep init #uid pid ppid C…

英语_阅读_Start school_待读

When children start school for the first time, parents often feel a sense of excitement coupled with a touch of sadness at the end of an era. This is the start of a new adventure for children playing a…

2025.10.20总结

今天继续学软考相关内容,目前过完操作系统剩下的相关知识 上午上课的时候进行项目演示有很多的收获,与它们的项目相比我目前的开发而言还存在很多的不足 操作系统作为系统资源的管理者,当然也需要对内存进行管理,要…

10.20总结

class Mammal{} class Dog extends Mammal {} class Cat extends Mammal{} public class TestCast { public static void main(String args[]) { Mammal m; Dog d=new Dog(); Cat c=new Cat(); m=d; //d=m; d=(Dog)m; …

学习相关

博客园主题设置 参考 一个是这个博主的,设置的比较精美:https://www.cnblogs.com/huxingxin/p/16886323.html 还有就是这个博主:https://www.cnblogs.com/zhaohongbing/p/16332606.html 其实自己也想照着这个博主的…

题解:Luogu P2075 区间 LIS

题意 给定长度为 \(n\) 的排列 \(p\),\(q\) 次询问 \(l,r\),求 \(p[l,r]\) 的 LIS 长度。\(1\leq n,q\leq 10^5\)。 题解 挺牛的题。 考虑如何刻画 LIS。感觉上 DP 没有什么前途,考虑另一种经典的 \(\mathcal{O}(n\…

英语_阅读_2050 Space tourism_待读

It is 2050. Space tourism has become a reality. 现在是2050年。太空旅游已经成为现实。 So would you want to be a space tourist? 那么你想成为一名太空游客吗? Here, some middle school students share their…

题解:Luogu P10644 [NordicOI 2022] 能源网格 Power Grid

题意 给定 \(n,m\)。对于 \(n\times m\) 的网格 \(a\),定义 \[c_{i,j}=\left\lvert \sum_{k=1}^{n}a_{k,j}-\sum_{k=1}^{m}a_{i,k} \right\rvert \]现在给定 \(c\),构造一组合法的 \(a\)。数据保证有解。\(1\leq n,m…

题解:Luogu P10004 [集训队互测 2023] Permutation Counting 2

题意 给定 \(n\),对于所有 \(0\leq x,y<n\) 求有多少长度为 \(n\) 的排列 \(p\) 满足 \(\sum\limits_{i=1}^{n-1}[p_i<p_{i+1}]=x\) 且 \(\sum\limits_{i=1}^{n-1}[p^{-1}_i<p^{-1}_{i+1}]=y\),答案对给定的…

题解:Luogu P4143 采集矿石

题意 给定长度为 \(n\) 的字符串 \(s\) 和权值序列 \(v\)。求所有子串 \(s[l,r]\) 使得 \(s[l,r]\) 在所有子串去重后的字典序降序排名,恰好等于 \(v[l,r]\) 的区间和。\(1\leq n\leq 10^5\)。 题解 注意到固定左端点…

从18w到1600w播放量,我的一点思考。

你好呀,我是歪歪。 前几天我想要巩固一下共识算法这个知识点。 (先声明,这篇文章不深入讨论共识算法本身) 于是我在 B 站大学上搜索了“共识算法”这个词:我还特意按照播放量排序了一下,准备先找个播放量高点的视…

扣一个细节问题

请看下这个uint bits = 0; for (int y = 0; y < 5; y++) {for (int x = 0; x < 4; x++)bits |= b[y][x] << (y * 4 + x);}上面的代码把一个[5][4]的byte数组用bits表示,该数组里的元素非0即1. 在经典的Th…

10.20java作业

10.20java作业1.2.3.4.5. 结果Parent: myValue = 10 Child: myValue = 20 Child: myValue = 20 Child: myValue = 20 Child: myValue = 21 第一行输出:new Parent() 创建父类对象,调用父类的 printValue 方法,输出父…

题解:Luogu P14175 【MX-X23-T5】向死存魏

题意 给定长度为 \(n\) 的序列 \(a\) 和值域 \(V\)。有 \(m\) 次操作:给定 \(l,r,x\),将 \(a[l,r]\) 中 \(=x\) 的数改为 \(0\)。 给定 \(x\),在序列末尾添加 \(x\)。 给定 \(l\),查询最小的 \(r\) 使得 \(a[l,r]\…

软工第三次作业————结对作业

软工第三次作业————结对作业软工第三次作业--结对作业 软工第三次作业结对作业——实现一个自动生成小学四则运算题目的命令行程序(也可以用图像界面,具有相似功能)项目作业 实现一个自动生成小学四则运算题目的…

Spring 常见注解

目录🧐 @Configuration 和 @Import 的核心区别详细解释1. @Configuration (配置类)2. @Import (引入)参考资料 🧐 @Configuration 和 @Import 的核心区别特性 @Configuration @Import主要目的 标记一个类是 Java 配…

题解:AtCoder ARC208C Mod of XOR

题意 给定 \(C,X\),构造一个 \(n(1\leq n<2^{60})\) 使得 \((n\oplus C)\bmod{n}=X\),或报告无解。多测,\(1\leq T\leq 2\times 10^5\),\(1\leq C,X<2^{30}\)。 题解 神人构造题。 显然要有 \(n>X\)。不妨…

题解:Luogu P6898 [ICPC 2014 WF] Metal Processing Plant

题意 给定 \(n\),对于每个 \(1\leq i,j\leq n\),给出 \(d(i,j)\)。对于集合 \(S\),定义 \(D(S)=\max\limits_{i,j\in S}d(i,j)\)。将 \(\{1,2,\cdots,n\}\) 划分为两个集合 \(A,B\),最小化 \(D(A)+D(B)\)。\(1\leq…

32-腾讯IM接入资料和定价

腾讯IM接入资料和定价信息 一、产品概述 腾讯云即时通信IM(Instant Messaging)是腾讯提供的企业级即时通讯服务,支持多种平台接入,包括Android、iOS、Web和小程序等。 二、定价信息 1. 基础服务资费体验版: 提供完…