WPF datagrid load data from WCF via json, export selected items to json file
//WPF <Window x:Class="WpfApp4.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:WpfApp4" mc:Ignorable="d" Title="{Binding MainTitle}" WindowState="Maximized"> <Window.DataContext> <local:MainVM/> </Window.DataContext> <Window.Resources> <Style TargetType="TextBlock" x:Key="TbkStyle"> <Setter Property="FontSize" Value="30"/> <Setter Property="FontWeight" Value="Normal"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Foreground" Value="Red"/> <Setter Property="FontWeight" Value="ExtraBold"/> </Trigger> </Style.Triggers> </Style> <ControlTemplate TargetType="ContentControl" x:Key="DGControlTemplate"> <DataGrid ItemsSource="{Binding BksCollection}" AutoGenerateColumns="True" CanUserAddRows="False" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.CacheLength="2,2" VirtualizingPanel.CacheLengthUnit="Item" ScrollViewer.CanContentScroll="True" ScrollViewer.IsDeferredScrollingEnabled="True" UseLayoutRounding="True" SnapsToDevicePixels="True"> <DataGrid.Resources> <Style TargetType="DataGridRow"> <Setter Property="FontSize" Value="30"/> <Setter Property="FontWeight" Value="Normal"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Foreground" Value="Red"/> <Setter Property="FontWeight" Value="ExtraBold"/> </Trigger> </Style.Triggers> </Style> </DataGrid.Resources> <DataGrid.ContextMenu> <ContextMenu> <MenuItem Header="Load Data" Command="{Binding LoadCommand}" FontSize="30" Width="300"/> <MenuItem Header="Export Selected" Command="{Binding ExportSelectedDataCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItems}" Width="300" FontSize="30"/> </ContextMenu> </DataGrid.ContextMenu> </DataGrid> </ControlTemplate> </Window.Resources> <Grid> <ContentControl Template="{StaticResource DGControlTemplate}"/> </Grid> </Window> using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.Eventing.Reader; using System.IO; using System.Net.Http; 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 Microsoft.Win32; using Newtonsoft.Json; namespace WpfApp4 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } public class MainVM : INotifyPropertyChanged { private static HttpClient client = new HttpClient() { Timeout = TimeSpan.FromHours(1) }; private static string originUrl = "http://localhost:59166/BookService.svc/getbooks?cnt="; private bool isLoading = false; private string tempMsg = ""; public MainVM() { if (!DesignerProperties.GetIsInDesignMode(new DependencyObject())) { SetMainTitle(GetTimeNow()); _ = InitBooksCollectionAsync(); } } private async Task InitBooksCollectionAsync(int cnt = 1000000) { if (isLoading) { return; } isLoading = true; tempMsg = $"{GetTimeNow()},start loading..."; SetMainTitle(tempMsg); try { string url = $"{originUrl}{cnt}"; string jsonStr = await client.GetStringAsync(url); List<Book> bksList = JsonConvert.DeserializeObject<List<Book>>(jsonStr); if (bksList != null && bksList.Any()) { BksCollection = new ObservableCollection<Book>(bksList); tempMsg = $"{GetTimeNow()},FirstId:{BksCollection?.FirstOrDefault()?.Id}," + $"LastId:{BksCollection?.LastOrDefault()?.Id}"; SetMainTitle(tempMsg); } } catch (Exception ex) { MessageBox.Show(ex?.Message); } finally { isLoading = false; } } private ICommand loadCommand; public ICommand LoadCommand { get { if(loadCommand==null) { loadCommand = new DelegateCommand(LoadCommandExecuted); } return loadCommand; } } private void LoadCommandExecuted(object obj) { _ = InitBooksCollectionAsync(); } private ICommand exportSelectedDataCommand; public ICommand ExportSelectedDataCommand { get { if(exportSelectedDataCommand==null) { exportSelectedDataCommand = new DelegateCommand(ExportSelectedDataCommandExecuted); } return exportSelectedDataCommand; } } private void ExportSelectedDataCommandExecuted(object obj) { var items = ((System.Collections.IList)obj).Cast<Book>()?.ToList(); if(items!=null && items.Any()) { string jsonStr = JsonConvert.SerializeObject(items, Formatting.Indented); SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Json Files|*.json|All Files|*.*"; dlg.FileName = $"Json_{GetTimeNow()}.json"; if (dlg.ShowDialog() == true) { using (StreamWriter jsonWriter = new StreamWriter(dlg.FileName, false, System.Text.Encoding.UTF8)) { jsonWriter.WriteLine(jsonStr); tempMsg = $"{GetTimeNow()},export {items.Count} items to {dlg.FileName}"; SetMainTitle(tempMsg); MessageBox.Show(tempMsg); } } } } private void SetMainTitle(string msg) { Application.Current?.Dispatcher.Invoke(() => { MainTitle = msg; }, System.Windows.Threading.DispatcherPriority.Background); } private ObservableCollection<Book> bksCollection; public ObservableCollection<Book> BksCollection { get { return bksCollection; } set { if (value != bksCollection) { bksCollection = value; OnPropertyChanged(); } } } private string mainTitle; public string MainTitle { get { return mainTitle; } set { if (value != mainTitle) { mainTitle = value; OnPropertyChanged(); } } } private string GetTimeNow() { return $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}"; } public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propName = "") { var handler = Volatile.Read(ref PropertyChanged); if (handler == null) { return; } handler(this, new PropertyChangedEventArgs(propName)); } } public class Book { public long Id { get; set; } public string Name { get; set; } public string CategoryName { get; set; } public string ISBN { get; set; } public string Comment { get; set; } public string Summary { get; set; } public string Title { get; set; } public string Topic { get; set; } } public class DelegateCommand : ICommand { private Action<object> execute; private Func<object?, bool>? canExecute; public DelegateCommand(Action<object> executeValue, Func<object?, bool>? canExecuteValue = null) { execute = executeValue; canExecute = canExecuteValue; } public event EventHandler? CanExecuteChanged; public bool CanExecute(object? parameter) { return canExecute == null ? true : canExecute(parameter); } public void Execute(object? parameter) { execute(parameter); } public void RaiseCanExecuted() { } } }
//WCF
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; using System.Text; namespace WcfService2 { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IBookService" in both code and config file together. [ServiceContract] public interface IBookService { [OperationContract] [WebGet(UriTemplate = "/getbooks?cnt={cnt}", RequestFormat =WebMessageFormat.Json, ResponseFormat =WebMessageFormat.Json)] List<Book> GetBooks(int cnt = 100); } public class Book { public long Id { get; set; } public string Name { get; set; } public string CategoryName { get; set; } public string ISBN { get; set; } public string Comment { get; set; } public string Summary { get; set; } public string Title { get; set; } public string Topic { get; set; } } enum BookCategory { Science, Technology, Engineering, Math } } using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using System.Threading; namespace WcfService2 { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "BookService" in code, svc and config file together. // NOTE: In order to launch WCF Test Client for testing this service, please select BookService.svc or BookService.svc.cs at the Solution Explorer and start debugging. public class BookService : IBookService { private static string[] enumNames = Enum.GetNames(typeof(BookCategory)); private static int enumsLen = enumNames.Length; private static Random rnd = new Random(); private static long id = 1; private static (long, long) GetStartEnd(int cnt = 1000) { long end = Interlocked.Add(ref id, cnt); long start = end - cnt; return (start, end); } public List<Book> GetBooks(int cnt = 100) { List<Book> bksList = new List<Book>(cnt); var (start, end) = GetStartEnd(cnt); for (long i = start; i < end; i++) { bksList.Add(new Book() { Id = i, Name = $"Name_{i}", CategoryName = $"{enumNames[rnd.Next(0, enumsLen)]}", ISBN = $"ISBN_{i}_{Guid.NewGuid():N}", Comment = $"Comment_{i}", Summary = $"Summary_{i}", Title = $"Title_{i}", Topic = $"Topic_{i}" }); } return bksList; } } } <?xml version="1.0"?> <configuration> <appSettings> <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> </appSettings> <system.web> <compilation debug="true" targetFramework="4.8" /> <httpRuntime targetFramework="4.8"/> </system.web> <system.serviceModel> <bindings> <webHttpBinding> <binding name="BookServiceWebHttpBinding" openTimeout="01:00:00" closeTimeout="01:00:00" sendTimeout="01:00:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"> <readerQuotas maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="2147483647" maxNameTableCharCount="2147483647" maxStringContentLength="2147483647"/> <security mode="None"/> </binding> </webHttpBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="BookServiceBehavior"> <!-- To avoid disclosing metadata information, set the values below to false before deployment --> <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> <endpointBehaviors> <behavior name="BookServiceEndPointBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <protocolMapping> <add binding="basicHttpsBinding" scheme="https" /> </protocolMapping> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> <services> <service name="WcfService2.BookService" behaviorConfiguration="BookServiceBehavior"> <endpoint address="" binding="webHttpBinding" contract="WcfService2.IBookService" behaviorConfiguration="BookServiceEndPointBehavior" bindingConfiguration="BookServiceWebHttpBinding"/> </service> </services> </system.serviceModel> <system.webServer> <modules runAllManagedModulesForAllRequests="true"/> <!-- To browse web app root directory during debugging, set the value below to true. Set to false before deployment to avoid disclosing web app folder information. --> <directoryBrowse enabled="true"/> </system.webServer> </configuration>






浙公网安备 33010602011771号