WPF ContentControl template is ControlTemplate based on ListBox
Install-Package Newtonsoft.json
<Window x:Class="WpfApp12.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:WpfApp12" mc:Ignorable="d" Title="{Binding MainTitle}" WindowState="Maximized"> <Window.DataContext> <local:MainVM/> </Window.DataContext> <Window.Resources> <DataTemplate DataType="{x:Type local:Book}" x:Key="BookDataTemplate"> <Border BorderBrush="Cyan" BorderThickness="2" Margin="5,0,5,20"> <Grid Width="{x:Static SystemParameters.FullPrimaryScreenWidth}" Margin="5"> <Grid.Resources> <Style TargetType="TextBlock"> <Setter Property="FontSize" Value="30"/> <Setter Property="HorizontalAlignment" Value="Center"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Foreground" Value="Red"/> <Setter Property="FontWeight" Value="ExtraBold"/> </Trigger> </Style.Triggers> </Style> </Grid.Resources> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Text="{Binding Id}" Grid.Row="0" Grid.Column="0"/> <TextBlock Text="{Binding Name}" Grid.Row="0" Grid.Column="1"/> <TextBlock Text="{Binding CategoryName}" Grid.Row="0" Grid.Column="2"/> <TextBlock Text="{Binding Author}" Grid.Row="1" Grid.Column="0"/> <TextBlock Text="{Binding Topic}" Grid.Row="1" Grid.Column="1"/> <TextBlock Text="{Binding Title}" Grid.Row="1" Grid.Column="2"/> <TextBlock Text="{Binding Summary}" Grid.Row="2" Grid.Column="0"/> <TextBlock Text="{Binding Comment}" Grid.Row="2" Grid.Column="1"/> <TextBlock Text="{Binding Content}" Grid.Row="2" Grid.Column="2"/> <TextBlock Text="{Binding ISBN}" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3"/> </Grid> </Border> </DataTemplate> <ControlTemplate x:Key="LbxTemplate"> <ListBox ItemsSource="{Binding BksCollection}" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.CacheLength="5,5" VirtualizingPanel.CacheLengthUnit="Item" ScrollViewer.IsDeferredScrollingEnabled="True" ScrollViewer.CanContentScroll="True" UseLayoutRounding="True" ItemTemplate="{StaticResource BookDataTemplate}"> </ListBox> </ControlTemplate> </Window.Resources> <Grid> <ContentControl Template="{StaticResource LbxTemplate}"/> </Grid> </Window> using Newtonsoft.Json; using System.Collections.ObjectModel; using System.ComponentModel; using System.Net.Http; using System.Runtime.CompilerServices; using System.Text; using System.Text.Json.Serialization; 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 WpfApp12 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } public class MainVM : INotifyPropertyChanged { static string url = "http://172.17.0.172:5000/api/books/getbooks/1000000"; static HttpClient client = new HttpClient() { Timeout = TimeSpan.FromMinutes(1) }; private bool isLoading = false; public MainVM() { if(!DesignerProperties.GetIsInDesignMode(new DependencyObject())) { _ = AutoLoadDataAsync(); } } private async Task AutoLoadDataAsync() { while(true) { await LoadDataAsync(); await Task.Delay(1000); } } private async Task LoadDataAsync() { if(isLoading) { return; } isLoading = false; MainTitle = $"{DateTime.Now},loading..."; try { string jsonStr = await client.GetStringAsync(url); if (!string.IsNullOrWhiteSpace(jsonStr)) { var bks = JsonConvert.DeserializeObject<List<Book>>(jsonStr); if (bks != null && bks.Any()) { BksCollection = new ObservableCollection<Book>(bks); MainTitle = $"{DateTime.Now},loaded {BksCollection.Count} items," + $"FirstId:{BksCollection.FirstOrDefault()?.Id}," + $"LastId:{BksCollection.LastOrDefault()?.Id}"; } } } catch (Exception ex) { MessageBox.Show(ex?.Message); } finally { isLoading = false; } } private string mainTitle = $"{DateTime.Now}"; public string MainTitle { get { return mainTitle; } set { if(value!=mainTitle) { mainTitle = value; OnPropertyChanged(); } } } private ObservableCollection<Book> bksCollection; public ObservableCollection<Book> BksCollection { get { return bksCollection; } set { if(value!=bksCollection) { bksCollection = value; OnPropertyChanged(); } } } public event PropertyChangedEventHandler? PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propName="") { var handler=Volatile.Read(ref PropertyChanged); if(handler!=null) { handler(this, new PropertyChangedEventArgs(propName)); } } } 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 Topic { get; set; } public string Title { get; set; } public string Summary { get; set; } public string Comment { get; set; } public string Content { get; set; } } }



//WebAPI
//D:\C\WebApplication5\Models\Book.cs namespace WebApplication5.Models { 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 Topic { get; set; } public string Title { get; set; } public string Summary { get; set; } public string Comment { get; set; } public string Content { get; set; } } enum BookCategory { Science, Technology, Engineering, Math } } //D:\C\WebApplication5\Controllers\BooksController.cs using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using WebApplication5.Models; namespace WebApplication5.Controllers { [Route("api/[controller]")] [ApiController] public class BooksController : ControllerBase { private static string[] enumNames = Enum.GetNames(typeof(BookCategory)); private static int enumLen = enumNames.Length; private static long id = 1; 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}", CategoryName = $"{enumNames[i%enumLen]}", Comment=$"Comment_{i}", Content=$"Content_{i}", Summary=$"Summary_{i}", Author=$"Author_{i}", Title=$"Title_{i}", Topic=$"Topic_{i}", ISBN=$"ISBN_{i}_{Guid.NewGuid():N}" }); } Console.WriteLine($"In WebAPI,{DateTime.Now},FirstId:{bksList.FirstOrDefault()?.Id}," + $"LastId:{bksList.LastOrDefault()?.Id}"); return bksList; } } } //D:\C\WebApplication5\Program.cs namespace WebApplication5 { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.WebHost.UseKestrel(x => { x.ListenAnyIP(5000); x.ListenAnyIP(5001, o => { o.UseHttps(); }); }); 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(); } } }




浙公网安备 33010602011771号