WPF ListBox ItemTemplate load data from ASP..Net Core WebAPI
//WPF Install-Package Newtonsoft.json
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="{Binding MainTitle}" WindowState="Maximized">
<Window.DataContext>
<local:MainVM/>
</Window.DataContext>
<Window.Resources>
<local:LenConverter x:Key="LenConverter"/>
<Style TargetType="TextBlock" x:Key="TbkStyle">
<Setter Property="FontSize" Value="20"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Red"/>
<Setter Property="FontWeight" Value="ExtraBold"/>
</Trigger>
</Style.Triggers>
</Style>
<DataTemplate DataType="{x:Type local:Book}"
x:Key="BookDataTemplate">
<Border BorderBrush="Cyan"
BorderThickness="2"
Margin="5">
<Grid Margin="5"
Width="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth},
Converter={StaticResource LenConverter},ConverterParameter=2}">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.Resources>
<Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
</Grid.Resources>
<TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Id}"/>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Author}"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Comment}"/>
<TextBlock Grid.Row="2" Grid.Column="0" Text="{Binding Content}"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Author}"/>
<TextBlock Grid.Row="3" Grid.Column="0" Text="{Binding Summary}"/>
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding Title}"/>
<TextBlock Grid.Row="4" Grid.Column="0" Text="{Binding Topic}"/>
<TextBlock Grid.Row="4" Grid.Column="1" Text="{Binding CategoryName}"/>
</Grid>
</Border>
</DataTemplate>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ListBox Grid.Column="0"
ItemsSource="{Binding BksCollection}"
ItemTemplate="{StaticResource BookDataTemplate}"/>
<ListBox Grid.Column="1"
ItemsSource="{Binding BksCollection}"
ItemTemplate="{StaticResource BookDataTemplate}"/>
</Grid>
</Window>
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
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 WpfApp1
{
/// <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.145:5000/getbooks/1000000";
static HttpClient client = new HttpClient()
{
Timeout = TimeSpan.FromSeconds(60)
};
private static bool isLoading = false;
public MainVM()
{
if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
_ = LoadDataAsync();
}
}
private async Task LoadDataAsync()
{
if (isLoading)
{
return;
}
isLoading = true;
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:{bks.FirstOrDefault()?.Id}," +
$"LastId:{bks.LastOrDefault()?.Id}";
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex?.Message);
}
finally
{
isLoading = false;
}
}
private string mainTitle = $"{DateTime.Now},loading...";
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 LenConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (double.TryParse(value?.ToString(), out double result))
{
return result / 2;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
public class Book
{
public long Id { get; set; }
public string Name { get; set; }
public string ISBN { 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; }
public string CategoryName { get; set; }
}
}

//WebAPI
//D:\C\WebApplication1\Models\Book.cs
namespace WebApplication1.Models
{
public class Book
{
public long Id { get; set; }
public string Name { get; set; }
public string ISBN { 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; }
public string CategoryName { get; set; }
}
enum BookCategory
{
Science, Technology, Engineering, Math
}
}
//D:\C\WebApplication1\Controllers\BooksController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApplication1.Models;
namespace WebApplication1.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}",
ISBN=$"ISBN_{i}_{Guid.NewGuid():N}",
Author=$"Author_{i}",
Comment=$"Comment_{i}",
Content=$"Content_{i}",
Summary=$"Summary_{i}",
Title=$"Title_{i}",
Topic=$"Topic_{i}",
CategoryName = $"{enumNames[i%enumLen]}"
});
}
Console.WriteLine($"In ASP.Net Core WebAPI,{DateTime.Now},FirstId:{start},end:{end-1}");
return bksList;
}
}
}
//D:\C\WebApplication1\Program.cs
namespace WebApplication1
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseKestrel(x =>
{
x.ListenAnyIP(5000);
x.ListenAnyIP(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();
}
}
}


浙公网安备 33010602011771号