惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
N
Netflix TechBlog - Medium
V
Visual Studio Blog
博客园 - Franky
小众软件
小众软件
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 三生石上(FineUI控件)
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享
量子位
大猫的无限游戏
大猫的无限游戏
人人都是产品经理
人人都是产品经理
V
V2EX
The Cloudflare Blog
月光博客
月光博客
Last Week in AI
Last Week in AI
雷峰网
雷峰网
WordPress大学
WordPress大学
博客园 - 【当耐特】
博客园 - 聂微东
IT之家
IT之家
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

博客园 - FredGrit

WPF customize via three combied custom controls WPF DataGrid DataGridTemplateColumn DataTemplate ContentPresenter ContentTemplate WPF Customcontrol NumUpDownScroller WPF CustomControl override Template in Generic.xaml and invoke different style WPF HierarchicalDataTemplate customize via ToggleButton WPF DataGrid DataGridTemplateColumn DataTemplate call predefined DataTemplate via ContentPresenter and ContentTemplate WPF ListBox load data via contentcontrol an ItemTemplate WPF TreeView HierarchicalDataTemplate with grouped Data WPF display grouped data with GroupBox and ItemsControl WPF two listbox scroll syncchronously via behavior WPF invoke data from WebAPI,DataGridTemplate call pre defined DataTemplate via ContentPresenter WPF ListBox load data from WCF WPF datagrid load data from WCF via json, export selected items to json file WPF ItemsControl load data from WCF,DataTemplate, ContentControl WPF customize rotated wheel relentlessly via custom control WPF embed DataTemplate in HierchicalDataTemplate of TreeView WPF ContentControl, ItemsControl, ItemsPanelTemplate,VirtualizingStackPanel,convert xml string to List<T> WPF parse web.config recursively, TreeView and HierarchicalDataTemplate WPF Custom control in cs and Generic.xaml WPF ContextMenu independent visual tree resolved via Freezable implemented class WPF custom control GetTemplateChild vs FindName,NameScope separation between Logical Tree and Visual Tree, WPF ListBox ListView Datatemplate, parse xml to List via XmlSerializer and StringReader WPF TreeView HierarchicalDataTemplate, parse xml via traverse in XmlElement WPF parse xml via [XmRoot] and [XmlElement] attributes together, contentcontrol's template is ControlTemplate from Resources WPF ContentControl invoke Template from resource, reuse datatemplate WPF deserialize xml string as List via [XmlRoot] and [XmlElement] attribute WPF ContentControl Template WPF DatagridTemplate Binding DataTemplate WPF TreeView explicitly given key name to HierarchicalDataTemplate WPF, parse XMlDocument as List
WPF DataGrid load data from Asp.Net Core WebAPI
FredGrit · 2026-09-04 · via 博客园 - FredGrit

//WebAPI

//D:\C\WebApplication2\BooksController.cs

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using WebApplication2.Models;

namespace WebApplication2
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private static long id = 1;
        private static (long, long) GetStartEnd(int cnt)
        {
            var end = Interlocked.Add(ref id, cnt);
            var start = end - cnt;
            return (start, end);
        }

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


//D:\C\WebApplication2\Models\Book.cs
namespace WebApplication2.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;  }
    }
}

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

namespace WebApplication2
{
    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();
        }
    }
}
//

            var builder = WebApplication.CreateBuilder(args);

            builder.WebHost.UseKestrel(x =>
            {
                x.ListenLocalhost(5000);
                x.ListenLocalhost(5001, o =>
                {
                    o.UseHttps();
                });
            });
warn: Microsoft.AspNetCore.Server.Kestrel[0]
      Overriding address(es) 'https://localhost:7123, http://localhost:5062'. Binding to endpoints defined via IConfiguration and/or UseKestrel() instead.
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: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: D:\C\WebApplication2

image

//WPF

   <DataGrid.Columns>
       <DataGridTemplateColumn>
           <DataGridTemplateColumn.CellTemplate>
               <DataTemplate>
                   <ContentPresenter ContentTemplate="{StaticResource BookDataTemplate}"/>
               </DataTemplate>
           </DataGridTemplateColumn.CellTemplate>
       </DataGridTemplateColumn>
   </DataGrid.Columns>
Install-Package Newtonsoft.Json
<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"
        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="Foreground" Value="Red"/>
                    <Setter Property="FontWeight" Value="ExtraBold"/>
                </Trigger>
            </Style.Triggers>
        </Style>
        
        <DataTemplate DataType="{x:Type local:Book}"
                      x:Key="BookDataTemplate">
            <Grid Margin="5"
                  Width="{x:Static SystemParameters.PrimaryScreenWidth}">
                <Grid.Resources>
                    <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                </Grid.Resources>
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition MaxWidth="300"/>
                    <ColumnDefinition MaxWidth="300"/>
                </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 Author}" Grid.Row="0" Grid.Column="2"/>
                <TextBlock Text="{Binding ISBN}" Grid.Row="1" Grid.Column="0"/>
                <TextBlock Text="{Binding Comment}" Grid.Row="1" Grid.Column="1"/>
                <TextBlock Text="{Binding Content}" Grid.Row="1" Grid.Column="2"/>
                <TextBlock Text="{Binding Summary}" Grid.Row="2" Grid.Column="0"/>
                <TextBlock Text="{Binding Title}" Grid.Row="2" Grid.Column="1"/>
                <TextBlock Text="{Binding Topic}" Grid.Row="2" Grid.Column="2"/>
            </Grid>
        </DataTemplate>

        <ControlTemplate TargetType="ContentControl"
                         x:Key="DGTemplate">
            <DataGrid ItemsSource="{Binding BksCollection}"
                      VirtualizingPanel.IsVirtualizing="True"
                      VirtualizingPanel.VirtualizationMode="Recycling"
                      VirtualizingPanel.CacheLength="5,5"
                      VirtualizingPanel.CacheLengthUnit="Item"
                      ScrollViewer.CanContentScroll="True"
                      ScrollViewer.IsDeferredScrollingEnabled="True"
                      UseLayoutRounding="True"
                      SnapsToDevicePixels="True"
                      AutoGenerateColumns="False"
                      CanUserAddRows="False"
                      SelectionMode="Extended">
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <ContentPresenter ContentTemplate="{StaticResource BookDataTemplate}"/>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                </DataGrid.Columns>
                <DataGrid.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Export Selected as Json"
                                  Width="400"
                                  FontSize="30"
                                  Command="{Binding ExportSelectedAsJsonCommand}"
                                  CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
                            Path=PlacementTarget.SelectedItems}" />
                    </ContextMenu>
                </DataGrid.ContextMenu>
            </DataGrid>                      
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource DGTemplate}"/>
    </Grid>
</Window>


using Microsoft.Win32;
using Newtonsoft.Json;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Net.Http;
using System.Reflection.Metadata;
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 WpfApp5
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        string url = "http://localhost:5000/getbooks/";
        private static HttpClient client = new HttpClient()
        {
            Timeout = TimeSpan.FromHours(1)
        };

        private bool isLoading = false;

        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _ = AutoLoadBooksAsync();
            }
        }

        private async Task AutoLoadBooksAsync(int cnt = 1000000)
        {
            while (true)
            {
                await LoadBooksAsync();
                await Task.Delay(2000);
            }
        }

        private async Task LoadBooksAsync(int cnt = 1000000)
        {
            if (isLoading)
            {
                return;
            }
            isLoading = true;

            MainTitle = $"{DateTime.Now},loading...";
            try
            {
                string jsonStr = await client.GetStringAsync($"{url}{cnt}");
                var bks = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                if (bks != null && bks.Any())
                {
                    BksCollection = new ObservableCollection<Book>(bks);
                    MainTitle = $"{DateTime.Now},First Id:{BksCollection.FirstOrDefault()?.Id}," +
                        $"LastId:{BksCollection.LastOrDefault()?.Id}";
                    PrintMsg(MainTitle);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }
        }

        private ICommand exportSelectedAsJsonCommand;
        public ICommand ExportSelectedAsJsonCommand
        {
            get
            {
                if(exportSelectedAsJsonCommand==null)
                {
                    exportSelectedAsJsonCommand = new DelegateCommand(ExportSelectedAsJsonCommandExecuted);
                }
                return exportSelectedAsJsonCommand;
            }
        }

        private void ExportSelectedAsJsonCommandExecuted(object? obj)
        {
            var items = ((System.Collections.IList)obj).Cast<Book>()?.ToList();
            if(items!=null && items.Any())
            {
                SaveFileDialog dlg = new SaveFileDialog();
                dlg.Filter = $"Json Files|*.json|All Files|*.*";
                dlg.FileName = $"Selected{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.json";
                if(dlg.ShowDialog()==true)
                {
                    var jsonStr = JsonConvert.SerializeObject(items, Formatting.Indented);
                    using(StreamWriter writer=new StreamWriter(dlg.FileName,false,Encoding.UTF8))
                    {
                        writer.WriteLine(jsonStr);
                        MessageBox.Show($"Saved selected items to {dlg.FileName}");
                    }
                }
            }
        }

        private string mainTitle = $"{DateTime.Now}";
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if (value != mainTitle)
                {
                    mainTitle = value;
                    OnPropertyChanged();
                }
            }
        }

        private void PrintMsg(string msg)
        {
#if DEBUG
            System.Diagnostics.Debug.WriteLine(msg);
#else
            System.Diagnostics.Trace.WriteLine(msg);
#endif
        }

        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 this.PropertyChanged);
            if (handler == null)
            {
                return;
            }
            handler(this, new PropertyChangedEventArgs(propName));
        }
    }

    public class DelegateCommand : ICommand
    {
        private readonly Action<object?> execute;
        private readonly Func<object?, bool>? canExecute;
        public DelegateCommand(Action<object?> executeValue, Func<object?, bool>? canExecuteValue = null)
        {
            execute = executeValue ?? throw new ArgumentNullException(nameof(executeValue));
            canExecute = canExecuteValue;
        }

        public event EventHandler? CanExecuteChanged;

        public bool CanExecute(object? parameter)
        {
            return canExecute == null ? true : canExecute(parameter);
        }

        public void Execute(object? parameter)
        {
            execute(parameter);
        }

        public void RaiseCanExecuteChanged()
        {
            var handler = Volatile.Read(ref CanExecuteChanged);
            if (handler == null)
            {
                return;
            }

            var dispatcher = Application.Current.Dispatcher;
            if (dispatcher != null)
            {
                if (dispatcher.CheckAccess())
                {
                    handler(this, EventArgs.Empty);
                }
                else
                {
                    dispatcher.Invoke(() =>
                    {
                        handler(this, EventArgs.Empty);
                    }, System.Windows.Threading.DispatcherPriority.Background);
                }
            }
        }
    }

    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; }
    }
}

image

image

image

image