WPF Data Source invoke from web api

Install-Package Newtonsoft.json

 

public async Task GetServiceDataAsync()
{
    string bookUrl = "https://localhost:7205/api/book";
    using (HttpClient hclient = new HttpClient())
    {
        var booksJson = await hclient.GetStringAsync(bookUrl);

        if (!string.IsNullOrWhiteSpace(booksJson))
        {
            List<Book>? booksList = JsonConvert.DeserializeObject<List<Book>>(booksJson);
            if (booksList != null && booksList.Any())
            {
                BooksCollection = new ObservableCollection<Book>(booksList);
            }
        }
    }
}

 

 

<Window x:Class="WpfApp5.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:WpfApp5"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="MainWindow" Height="450" Width="800">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection}"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLength="5,5"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  AutoGenerateColumns="True"
                  CanUserAddRows="False"
                  EnableColumnVirtualization="True"
                  EnableRowVirtualization="True"
                  ScrollViewer.CanContentScroll="True"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  SelectionMode="Extended">
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <Setter Property="FontSize" Value="20"/>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="FontSize" Value="25"/>
                            <Setter Property="Foreground" Value="Red"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.RowStyle>
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Export All As Json"
                              Command="{Binding ExportAllAsJsonCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
                        Path=PlacementTarget.Items}"/>
                    <MenuItem Header="Export Selected As Json"
                              Command="{Binding ExportAsJsonCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},Path=PlacementTarget.SelectedItems}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
            
        </DataGrid>
    </Grid>
</Window>


using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Net;
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.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Newtonsoft.Json;

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

    public class MainVM : INotifyPropertyChanged
    {
        public MainVM()
        {
            GetServiceDataAsync();
        }



        public async Task GetServiceDataAsync()
        {
            string bookUrl = "https://localhost:7205/api/book";
            using (HttpClient hclient = new HttpClient())
            {
                var booksJson = await hclient.GetStringAsync(bookUrl);

                if (!string.IsNullOrWhiteSpace(booksJson))
                {
                    List<Book>? booksList = JsonConvert.DeserializeObject<List<Book>>(booksJson);
                    if (booksList != null && booksList.Any())
                    {
                        BooksCollection = new ObservableCollection<Book>(booksList);
                    }
                }
            }
        }

        private ICommand exportAsJsonCommand;
        public ICommand ExportAsJsonCommand
        {
            get
            {
                if (exportAsJsonCommand == null)
                {
                    exportAsJsonCommand = new DelCommand(ExportAsJsonCommandExecuted);
                }
                return exportAsJsonCommand;
            }
        }

        private ICommand exportAllAsJsonCommand;
        public ICommand ExportAllAsJsonCommand
        {
            get
            {
                if (exportAllAsJsonCommand == null)
                {
                    exportAllAsJsonCommand = new DelCommand(ExportAllAsJsonCommandExecuted);
                }
                return exportAllAsJsonCommand;
            }
        }

        private void ExportAllAsJsonCommandExecuted(object? obj)
        {
            var itemsList = ((System.Collections.IList)obj)?.Cast<Book>()?.ToList();
            if (itemsList != null && itemsList.Any())
            {
                string jsonStr = JsonConvert.SerializeObject(itemsList, Formatting.Indented);
                string jsonFile = $"JsonAll_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}";

                using (StreamWriter jsonWriter = new StreamWriter(jsonFile, false, Encoding.UTF8))
                {
                    jsonWriter.WriteLine(jsonStr);
                    MessageBox.Show($"Save json in {jsonFile}", $"{DateTime.Now}");
                }
            }
        }

        private void ExportAsJsonCommandExecuted(object? obj)
        {
            var bksList = ((System.Collections.IList)obj)?.Cast<Book>()?.ToList();
            if (bksList != null && bksList.Any())
            {
                string jsonStr = JsonConvert.SerializeObject(bksList, Formatting.Indented);
                string jsonFile = $"JsonSelected_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}";

                using (StreamWriter jsonWriter = new StreamWriter(jsonFile, false, Encoding.UTF8))
                {
                    jsonWriter.WriteLine(jsonStr);
                    MessageBox.Show($"Save json in {jsonFile}", $"{DateTime.Now}");
                }
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] 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();
                }
            }
        }
    }


    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?.Invoke(parameter);
        }
    }



    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ISBN { get; set; }
        public string Author { get; set; }
        public string Abstract { 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

 

 

image

 

posted @ 2026-03-15 00:42  FredGrit  阅读(18)  评论(0)    收藏  举报