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

推荐订阅源

Hugging Face - Blog
Hugging Face - Blog
腾讯CDC
阮一峰的网络日志
阮一峰的网络日志
博客园_首页
Last Week in AI
Last Week in AI
月光博客
月光博客
D
DataBreaches.Net
WordPress大学
WordPress大学
雷峰网
雷峰网
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 叶小钗
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
U
Unit 42
Recent Announcements
Recent Announcements
宝玉的分享
宝玉的分享
MyScale Blog
MyScale Blog
C
Check Point Blog
F
Fortinet All Blogs
B
Blog
小众软件
小众软件
Vercel News
Vercel News
罗磊的独立博客
有赞技术团队
有赞技术团队

博客园 - 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 DataGrid load data from Asp.Net Core WebAPI WPF TreeView HierarchicalDataTemplate with grouped Data WPF display grouped data with GroupBox and ItemsControl WPF two listbox scroll syncchronously via behavior 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 invoke data from WebAPI,DataGridTemplate call pre de...
FredGrit · 2026-08-30 · via 博客园 - FredGrit
//WebAPI
//D:\C\WebApplication1\WebApplication1\Book.cs
namespace WebApplication1
{
    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set;  }
        public string Author { get; set; }
        public string CategoryName { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string ISBN { get; set;  }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }

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


//D:\C\WebApplication1\WebApplication1\Controllers\BookController.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

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

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

        [HttpGet("getbooks/{cnt}")]
        public List<Book> GetBooks(int cnt=1000)
        {
            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}",
                    Summary=$"Summary_{i}",
                    CategoryName = $"{enumNames[i%enumsLen]}",
                    Author=$"Author_{i}",
                    Title=$"Title_{i}",
                    Topic=$"Topic_{i}"
                });
            }
            Console.WriteLine($"{DateTime.Now},Start:{start},End:{end}");
            return bksList;
        }
    }
}
<DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate >
                            <ContentPresenter Content="{Binding}"
                                              ContentTemplate="{StaticResource BookDataTemplate}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
//WPF
//D:\C\WpfApp1\WpfApp1\MainWindow.xaml
<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:LenSubtractConverter x:Key="LenSubtractConverter"/>
        
        <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">
            <!--<Border BorderBrush="LightGray"
                    BorderThickness="3"
                    Margin="5">-->
                <Grid Margin="5"
                      Width="{Binding DataContext.WinContentWidth,RelativeSource={RelativeSource AncestorType=Window}}"                      
                      Height="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight},
                      Converter={StaticResource LenSubtractConverter},ConverterParameter=5}">
                    <Grid.Resources>
                        <Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
                    </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 Author}" Grid.Row="0" Grid.Column="2"/>
                    <TextBlock Text="{Binding CategoryName}" 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"/>
                    <TextBlock Text="{Binding ISBN}" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3"/>
                </Grid>
            <!--</Border>-->
        </DataTemplate>

        <Style TargetType="DataGridRow">
            <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>
    </Window.Resources>
    <Grid>        
        <DataGrid ItemsSource="{Binding BksCollection}"
                  RowDetailsTemplate="{StaticResource BookDataTemplate}"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLength="5,5"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  ScrollViewer.CanContentScroll="True"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  UseLayoutRounding="True"
                  SnapsToDevicePixels="True"
                  >
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate >
                            <ContentPresenter Content="{Binding}"
                                              ContentTemplate="{StaticResource BookDataTemplate}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
            <DataGrid.ContextMenu>
                <ContextMenu>
                    <MenuItem Header="Load Data"
                              Width="300"
                              FontSize="30"
                              Command="{Binding LoadDataCommand}"/>
                </ContextMenu>
            </DataGrid.ContextMenu>
        </DataGrid>

    </Grid>
</Window>

//D:\C\WpfApp1\WpfApp1\MainWindow.xaml.cs

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
    {
        private MainVM vm;
        public MainWindow()
        {
            InitializeComponent();

            this.SizeChanged += MainWindow_SizeChanged;
        }

        private void MainWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            var vm = this.DataContext as MainVM;
            if (vm != null)
            {
                var elem = this.Content as FrameworkElement;
                if (elem != null)
                {
                    var tempWidth = this.ActualWidth;
                    vm.WinContentWidth = elem.ActualWidth;
                }
            }
        }
    }

    public class MainVM : INotifyPropertyChanged
    {
        private static HttpClient httpClient = new HttpClient()
        {
            Timeout = TimeSpan.FromHours(1)
        };

        static string url = "http://localhost:5000/api/book/getbooks/";
        private static bool isLoading = false;
        public MainVM()
        {
            if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                _ = AutoLoadDataAsync(1000000);
            }
        }

        private async Task AutoLoadDataAsync(int cnt = 1000000)
        {
            while(true)
            {
                try
                {
                    await InitBooksAsync(cnt);
                    await Task.Delay(20000);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex?.Message);                     
                }
            }
        }

        private ICommand loadDataCommand;
        public ICommand LoadDataCommand
        {
            get
            {
                if(loadDataCommand==null)
                {
                    loadDataCommand = new DelegateCommand(LoadDataCommandExecuted);
                }
                return loadDataCommand;
            }
        }

        private void LoadDataCommandExecuted(object? obj)
        {
            _ = InitBooksAsync(1000000);
        }

        private async Task InitBooksAsync(int cnt = 1000000)
        {
            if (isLoading)
            {
                return;
            }
            isLoading = true;
            MainTitle = $"{DateTime.Now},loading...";
            try
            {
                string jsonStr = await httpClient.GetStringAsync($"{url}{cnt}");
                if (string.IsNullOrWhiteSpace(jsonStr))
                {
                    return;
                }

                var bks = JsonConvert.DeserializeObject<List<Book>>(jsonStr);
                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 double winContentWidth = 0.0d;
        public double WinContentWidth
        {
            get
            {
                return winContentWidth;
            }
            set
            {
                if (value != winContentWidth)
                {
                    winContentWidth = value;
                    OnPropertyChanged();
                }
            }
        }

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

    public class Book
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string Author { get; set; }
        public string CategoryName { get; set; }
        public string Comment { get; set; }
        public string Content { get; set; }
        public string ISBN { get; set; }
        public string Summary { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }

    public class LenSubtractConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (double.TryParse(value?.ToString(), out double d1)
                && double.TryParse(parameter?.ToString(), out double d2)
                && d2 > 0)
            {
                return d1 / d2;
            }
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class DelegateCommand : ICommand
    {
        private Action<object?> execute;
        private Func<object?, bool>? canExecute;

        public DelegateCommand(Action<object?> executeValue, Func<object?, bool>? canExecuteValue=null)
        {
            execute = 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);
        }
    }
}

image

image

image

image