WPF retrieve data from ASP.NET Core WebAPI, ListBox selected item changes, DataGrid's ItemSource changed simultaneously

Install-Package Newtonsoft.Json

 

//WPF
//D:\C\WpfApp16\MainWindow.xaml

<Window x:Class="WpfApp16.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:WpfApp16"
        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"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="FontWeight" Value="ExtraBold"/>
                    <Setter Property="Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>

        <ControlTemplate TargetType="ContentControl"
                         x:Key="LbxTemplate">
            <ListBox ItemsSource="{Binding CategoryCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                     SelectedItem="{Binding SelectedCategory,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                     BorderBrush="LightBlue"
                     BorderThickness="2"
                     Margin="5"
                     VirtualizingPanel.IsVirtualizing="True"
                     VirtualizingPanel.VirtualizationMode="Recycling"
                     VirtualizingPanel.CacheLength="5,5"
                     VirtualizingPanel.CacheLengthUnit="Item"
                     ScrollViewer.IsDeferredScrollingEnabled="True"
                     ScrollViewer.CanContentScroll="True">
                <ListBox.ItemContainerStyle>
                    <Style TargetType="ListBoxItem">
                        <Setter Property="FontSize" Value="50"/>
                        <Setter Property="Height" Value="100"/>
                        <Setter Property="HorizontalAlignment" Value="Left"/>
                        <Setter Property="VerticalAlignment" Value="Center"/>
                        <Style.Triggers>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="FontWeight" Value="ExtraBold"/>
                                <Setter Property="Foreground" Value="Red"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </ListBox.ItemContainerStyle>
            </ListBox>
        </ControlTemplate>

        <ControlTemplate TargetType="ContentControl"                         
                         x:Key="DGTemplate">
            <DataGrid ItemsSource="{Binding BksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                      BorderBrush="LightBlue"
                      BorderThickness="2"
                      Margin="5"
                      Background="White"
                      AutoGenerateColumns="True"
                      CanUserAddRows="False"
                      VirtualizingPanel.IsVirtualizing="True"
                      VirtualizingPanel.VirtualizationMode="Recycling"
                      VirtualizingPanel.CacheLength="5,5"
                      VirtualizingPanel.CacheLengthUnit="Item"
                      UseLayoutRounding="True"
                      IsReadOnly="True">
                <DataGrid.CellStyle>
                    <Style TargetType="DataGridCell">
                        <Setter Property="FontSize" Value="30"/>
                        <Style.Triggers>
                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="Foreground" Value="Red"/>
                                <Setter Property="Background" Value="White"/>
                                <Setter Property="FontWeight" Value="ExtraBold"/>
                            </Trigger>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Foreground" Value="Blue"/>
                            </Trigger>
                        </Style.Triggers>
                    </Style>
                </DataGrid.CellStyle>
            </DataGrid>
        </ControlTemplate>

    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="4*"/>
        </Grid.ColumnDefinitions>

        <ContentControl Grid.Column="0"
                        Template="{StaticResource LbxTemplate}"/>

        <ContentControl Grid.Column="1"
                        Template="{StaticResource DGTemplate}"/>
    </Grid>
</Window>


//D:\C\WpfApp16\MainWindow.xaml.cs
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
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;

namespace WpfApp16
{
    /// <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 url = "https://localhost:5001/api/books/getbooks/";

        private List<Book> bks = new List<Book>();
        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _ = LoadBksAsync();
            }
        }
        private async Task LoadBksAsync(int cnt = 1000000)
        {
            try
            {
                string jsonStr = await client.GetStringAsync($"{url}{cnt}");
                if (!string.IsNullOrWhiteSpace(jsonStr))
                {
                    bks = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                    if (bks != null && bks.Any())
                    {
                        CategoryCollection = new ObservableCollection<string>(bks.Select(x => x.CategoryName).Distinct());
                        SelectedCategory = CategoryCollection.FirstOrDefault();
                        var selectedBksList = bks.Where(x => string.Equals(x.CategoryName, SelectedCategory, StringComparison.InvariantCultureIgnoreCase)).ToList();
                        BksCollection = new ObservableCollection<Book>(selectedBksList);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
        }

        private ObservableCollection<Book> bksCollection;
        public ObservableCollection<Book> BksCollection
        {
            get
            {
                return bksCollection;
            }
            set
            {
                if (value != bksCollection)
                {
                    bksCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        private ObservableCollection<string> categoryCollection;
        public ObservableCollection<string> CategoryCollection
        {
            get
            {
                return categoryCollection;
            }
            set
            {
                if (value != categoryCollection)
                {
                    categoryCollection = value;
                    OnPropertyChanged();
                }
            }
        }

        private string selectedCategory;
        public string SelectedCategory
        {
            get
            {
                return selectedCategory;
            }
            set
            {
                if (value != selectedCategory)
                {
                    selectedCategory = value;
                    OnPropertyChanged();
                    OnSelectedCategoryChanged();
                }
            }
        }

        private string mainTitle;
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if (value != mainTitle)
                {
                    mainTitle = value;
                    OnPropertyChanged();
                }
            }
        }

        private void OnSelectedCategoryChanged()
        {
            if (bks != null && bks.Any() && !string.IsNullOrWhiteSpace(SelectedCategory))
            {
                MainTitle = $"Selected Category:{SelectedCategory}";
                var selectedBksList = bks.Where(x => string.Equals(x.CategoryName, SelectedCategory, StringComparison.InvariantCultureIgnoreCase)).ToList();
                BksCollection = new ObservableCollection<Book>(selectedBksList);
            }
        }

        public event PropertyChangedEventHandler? PropertyChanged;
        private void OnPropertyChanged([CallerMemberName] string propeName = "")
        {
            var handler = Volatile.Read(ref PropertyChanged);
            if (handler == null)
            {
                return;
            }
            handler(this, new PropertyChangedEventArgs(propeName));
        }
    }

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

 

 

 

 

 

image

 

 

//WebAPI

//D:\C\WebApplication7\Controllers\BooksController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace WebApplication7.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private static long id = 1;
        private static string[] enumNames = Enum.GetNames(typeof(BookCategory));
        private static int enumLen = enumNames.Length;

        private static (long, long) GetStartEnd(int cnt = 1000000)
        {
            long end = Interlocked.Add(ref id, cnt);
            long start = end - cnt;
            return (start, end);
        }

        [HttpGet("getbooks/{cnt}")]
        public List<Book> GetBooks(int cnt = 1000000)
        {
            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}",
                    ISBN = $"ISBN_{i}_{Guid.NewGuid():N}",
                    Comment = $"Comment_{i}",
                    Content = $"Content_{i}",
                    Author = $"Author_{i}",
                    Summary = $"Summary_{i}",
                    Title = $"Title_{i}",
                    Topic = $"Topic_{i}",
                    CategoryName = $"{enumNames[i % enumLen]}"
                });
            }

            Console.WriteLine($"WebAPI:{DateTime.Now},count:{bksList.Count}," +
                $"FirstId:{bksList.FirstOrDefault()?.Id}," +
                $"LastId:{bksList.LastOrDefault()?.Id}");
            return bksList;
        }
    }

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

    enum BookCategory
    {
        Sciencen, Technology, Engineering, Math
    }
}


//D:\C\WebApplication7\Program.cs

namespace WebApplication7
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            builder.WebHost.UseKestrel(x =>
            {
                x.ListenLocalhost(5000);
                x.ListenLocalhost(5001, o =>
                {
                    o.UseHttps();
                });
            });
            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
            builder.Services.AddOpenApi();

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.MapOpenApi();
            }

            //app.UseHttpsRedirection();

            app.UseAuthorization();


            app.MapControllers();

            app.Run();
        }
    }
}

 

 

info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: https://localhost:5001
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: D:\C\WebApplication7\bin\Release\net10.0
WebAPI:2026-09-13 15:15:17,count:100000,FirstId:1,LastId:100000
WebAPI:2026-09-13 15:16:23,count:100000,FirstId:100001,LastId:200000
WebAPI:2026-09-13 15:48:45,count:1000000,FirstId:200001,LastId:1200000
WebAPI:2026-09-13 15:50:18,count:1000000,FirstId:1200001,LastId:2200000
WebAPI:2026-09-13 15:51:53,count:1000000,FirstId:2200001,LastId:3200000
WebAPI:2026-09-13 15:53:34,count:1000000,FirstId:3200001,LastId:4200000
WebAPI:2026-09-13 15:54:46,count:1000000,FirstId:4200001,LastId:5200000
WebAPI:2026-09-13 15:56:32,count:1000000,FirstId:5200001,LastId:6200000
WebAPI:2026-09-13 16:00:08,count:1000000,FirstId:6200001,LastId:7200000
WebAPI:2026-09-13 16:01:15,count:1000000,FirstId:7200001,LastId:8200000
WebAPI:2026-09-13 16:03:06,count:1000000,FirstId:8200001,LastId:9200000
WebAPI:2026-09-13 16:04:09,count:1000000,FirstId:9200001,LastId:10200000
WebAPI:2026-09-13 16:04:53,count:1000000,FirstId:10200001,LastId:11200000
WebAPI:2026-09-13 16:05:22,count:1000000,FirstId:11200001,LastId:12200000
WebAPI:2026-09-13 16:05:38,count:1000000,FirstId:12200001,LastId:13200000
WebAPI:2026-09-13 16:06:26,count:1000000,FirstId:13200001,LastId:14200000
WebAPI:2026-09-13 16:06:52,count:1000000,FirstId:14200001,LastId:15200000

 

 

image

 

posted @ 2026-09-13 16:14  FredGrit  阅读(6)  评论(0)    收藏  举报