WPF itemscontrol set ScrollViewer CanContentScroll=True explicitly to open virtualization so that it can hold 1M data

 <Window x:Class="WpfApp13.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:WpfApp13"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" WindowState="Maximized">
    <Window.DataContext>
        <local:MainVM/>
    </Window.DataContext>
    <Window.Resources>
        <DataTemplate x:Key="BkTemplate"
                      DataType="{x:Type local:Book}">
            <Border Margin="10"
                    BorderBrush="Cyan"
                    BorderThickness="3"
                    Width="{x:Static SystemParameters.FullPrimaryScreenWidth}">
                <Grid Margin="5">
                    <Grid.Resources>
                        <Style TargetType="TextBlock">
                            <Setter Property="FontSize" Value="30"/>
                            <Setter Property="HorizontalAlignment" Value="Center"/>
                            <Setter Property="VerticalAlignment" 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/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Id}"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>
                    <TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding CategoryName}"/>
                    <TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Author}"/>
                    <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Topic}"/>
                    <TextBlock Grid.Row="1" Grid.Column="2" Text="{Binding Title}"/>
                    <TextBlock Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="3" Text="{Binding ISBN}"/> 
                </Grid>
            </Border>
        </DataTemplate>

        <ControlTemplate TargetType="ContentControl" x:Key="ItemsControlTemplate">
            <ItemsControl ItemsSource="{Binding BksCollection}"
                          ItemTemplate="{StaticResource BkTemplate}"                         
                          VirtualizingPanel.IsVirtualizing="True"
                          VirtualizingPanel.VirtualizationMode="Recycling">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.Template>
                    <ControlTemplate>
                        <ScrollViewer CanContentScroll="True">
                            <ItemsPresenter/>
                        </ScrollViewer>
                    </ControlTemplate>
                </ItemsControl.Template>
            </ItemsControl>
        </ControlTemplate>
    </Window.Resources>
    <Grid>
        <ContentControl Template="{StaticResource ItemsControlTemplate}"/>
    </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 WpfApp13
{
    /// <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 static 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 = 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:{bks.Count} items," +
                            $"FirstId:{bks.FirstOrDefault()?.Id}," +
                            $"LastId:{bks.LastOrDefault()?.Id}";
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex?.Message);
            }
            finally
            {
                isLoading = false;
            }
        }

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

        private string mainTitle = $"{DateTime.Now}";
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                if(value!=mainTitle)
                {
                    mainTitle = 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; }
    }
}

 

 

Install-Package Newtonsoft.Json

 

 

 

image

 

 

 

 

image

 

 

 

image

 

posted @ 2026-10-02 19:59  FredGrit  阅读(2)  评论(0)    收藏  举报