WPF consume http json and update periodically via DispatcherTimer

Install-Package Newtonsoft.json

 

<Window x:Class="WpfApp30.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:WpfApp30"
        mc:Ignorable="d"
        Title="{Binding MainTitle}"
        WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection}"
                  AutoGenerateColumns="True"
                  CanUserAddRows="False"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLength="2,2"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  ScrollViewer.CanContentScroll="True"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  EnableRowVirtualization="True"
                  EnableColumnVirtualization="True"
                  UseLayoutRounding="True"
                  SnapsToDevicePixels="True"
                  SelectionMode="Extended"
                  >
            <DataGrid.Resources>
                <Style TargetType="DataGridRow">
                    <Setter Property="FontSize" Value="30"/>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="FontSize" Value="50"/>
                            <Setter Property="Foreground" Value="Red"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.Resources>
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Save">
                        <MenuItem Header="Save as Json"
                                  Command="{Binding SaveJsonCmd}"
                                  CommandParameter="{Binding Path=PlacementTarget.SelectedItems,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}"/>
                        <MenuItem Header="Save as CSV"
                                  Command="{Binding SaveCSVCmd}"
                                  CommandParameter="{Binding Path=PlacementTarget.SelectedItems,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}"/>
                    </MenuItem>
                </ContextMenu>
            </DataGrid.ContextMenu>
        </DataGrid>                  
    </Grid>
</Window>


using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
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.Windows.Threading;

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

    public class MainVM : INotifyPropertyChanged
    {
        private HttpClient client;
        private DispatcherTimer tmr;
        private string apiUrl = "http://localhost:55548/getbookslist?cnt=";
        public ICommand SaveJsonCmd { get; set;  }
        public ICommand SaveCSVCmd { get; set;  }
        public MainVM()
        {
            client = new HttpClient();
            Task.Run(async () =>
            {
                await InitBooksCollectionAsync();
            });
            InitTimer();
            InitCommands();
        }

        private void InitCommands()
        {
            SaveJsonCmd = new DelCmd(SaveJsonCmdExecuted);
            SaveCSVCmd = new DelCmd(SaveCSVCmdExecuted);
        }

        private void SaveCSVCmdExecuted(object? obj)
        {
            
        }

        private void SaveJsonCmdExecuted(object? obj)
        {
            var items = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            if(items!=null && items.Any())
            {
                string jsonFile = $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json";
                string jsonStr=JsonConvert.SerializeObject(items, Formatting.Indented);
                using(StreamWriter jsonWriter=new StreamWriter(jsonFile,false,Encoding.UTF8))
                {
                    jsonWriter.WriteLine(jsonStr);
                    string msg = $"{DateTime.Now},save {items.Count} items in json file {jsonFile}";
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        MessageBox.Show(msg);
                    });                    
                }
            }
        }

        private void InitTimer()
        {
            tmr = new DispatcherTimer();
            tmr.Tick += async (s, e) =>
            {
                await InitBooksCollectionAsync();
            };
            tmr.Interval = TimeSpan.FromSeconds(60);
            tmr.Start();
        }

        private async Task InitBooksCollectionAsync(int cnt=1000000)
        {
            string jsonStr = await client.GetStringAsync($"{apiUrl}{cnt}");
            BooksCollection=new ObservableCollection<Book>(JsonConvert.DeserializeObject<List<Book>>(jsonStr));
            MainTitle = $"{DateTime.Now},loaded {BooksCollection.Count} items,first Id:{BooksCollection.FirstOrDefault()?.Id},Last Id:{BooksCollection.LastOrDefault()?.Id}";
        }

        private string mainTitle=$"{DateTime.Now},loading...";
        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 event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName]string propName="")
        {
            var handler = PropertyChanged;
            handler?.Invoke(this, new PropertyChangedEventArgs(propName));
        }
    }

    public class DelCmd : ICommand
    {
        private Action<object?>? execute;
        private Predicate<object?>? canExecute;
        public DelCmd(Action<object?>? executeValue, Predicate<object?>? canExecuteValue=null)
        {
            execute = executeValue ?? throw new ArgumentNullException(nameof(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?.Invoke(parameter);
        }
    }


    [DataContract]
    public class Book
    {
        [DataMember(IsRequired = true, Order = 1)]
        public long Id { get; set; }

        [DataMember(IsRequired = true, Order = 2)]
        public string Author { get; set; }

        [DataMember(IsRequired = true, Order = 3)]
        public string Abstract { get; set; }

        [DataMember(IsRequired = true, Order = 4)]
        public string Name { get; set; }

        [DataMember(IsRequired = true, Order = 5)]
        public string ISBN { get; set; }

        [DataMember(IsRequired = true, Order = 6)]
        public string Title { get; set; }

        [DataMember(IsRequired = true, Order = 7)]
        public string Topic { get; set; }

        [DataMember(IsRequired = true, Order = 8)]
        public string Comment { get; set; }

        [DataMember(IsRequired = true, Order = 9)]
        public string Content { get; set; }

        [DataMember(IsRequired = true, Order = 10)]
        public string Summary { get; set; }
    }
}

 

 

 

 

image

 

 

 

 

image

 

posted @ 2026-05-14 17:00  FredGrit  阅读(11)  评论(0)    收藏  举报