WPF datagrid mvvm loaded 100M items,prism.wpf,prism.dryioc

Install-Package Prism.Wpf
Install-Package Prism.DryIOC
#region Interfaces
public interface IIDService
{
    int GetID();
}

public class IDService : IIDService
{
    int idx = 0;
    public int GetID()
    {
        return Interlocked.Increment(ref idx);
    }
}

public interface INameService
{
    string GetName();
}

public class NameService : INameService
{
    int idx = 0;
    public string GetName()
    {
        return $"Name_{Interlocked.Increment(ref idx)}";
    }
}

public interface IISBNService
{
    string GetISBN();
}

public class ISBNService : IISBNService
{
    int idx = 0;
    public string GetISBN()
    {
        return $"ISBN_{Interlocked.Increment(ref idx)}";
    }
}

#endregion


using System.Configuration;
using System.Data;
using System.Windows;

namespace WpfApp39
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<IIDService, IDService>();
            containerRegistry.RegisterSingleton<INameService, NameService>();
            containerRegistry.RegisterSingleton<IISBNService,ISBNService>();
            containerRegistry.RegisterSingleton<MainWindow>();
            containerRegistry.RegisterSingleton<MainWindowViewModel>();
        }
    }

}
 public async Task InitBooksCollectionAsync()
 {
     BooksCollection = new ObservableCollection<Book>();
     List<Book> booksList = new List<Book>();
     for (int i = 1; i < 100000001; i++)
     {
         booksList.Add(new Book()
         {
             Id=idService.GetID(),
             Name=nameService.GetName(),
             ISBN=isbnService.GetISBN(),
             Title=$"Title_{i}",
             Topic=$"Topic_{i}"
         });

         if(i%1000000==0)
         {
             await PopulateBooksCollectionAsync(booksList);
         }
     }
 }

 private async Task PopulateBooksCollectionAsync(List<Book> booksList)
 {
     await Application.Current.Dispatcher.InvokeAsync(() =>
     {
         var tempList = booksList.ToList();
         booksList.Clear();
         foreach (var bk in tempList)
         {
             BooksCollection.Add(bk);
         }
         MainTitle = $"Loaded {BooksCollection.Count} items,{GetMemory()}";
     }, System.Windows.Threading.DispatcherPriority.Background);
 }

 private string GetMemory()
 {
     var mem = Process.GetCurrentProcess().PrivateMemorySize64 / 1024.0d / 1024.0d;
     return $"Memory:{mem.ToString("N2")} M";
 }

 

 

//App
<prism:PrismApplication x:Class="WpfApp39.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp39"
             xmlns:prism="http://prismlibrary.com/">    
</prism:PrismApplication>
using System.Configuration;
using System.Data;
using System.Windows;

namespace WpfApp39
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<IIDService, IDService>();
            containerRegistry.RegisterSingleton<INameService, NameService>();
            containerRegistry.RegisterSingleton<IISBNService,ISBNService>();
            containerRegistry.RegisterSingleton<MainWindow>();
            containerRegistry.RegisterSingleton<MainWindowViewModel>();
        }
    }

}


<Window x:Class="WpfApp39.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:WpfApp39"
        xmlns:prism="http://prismlibrary.com/"
        mc:Ignorable="d"
        Title="{Binding MainTitle}" Height="450" Width="800"
        WindowState="Maximized"
        prism:ViewModelLocator.AutoWireViewModel="True">
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                  VirtualizingPanel.IsVirtualizing="True"
                  VirtualizingPanel.VirtualizationMode="Recycling"
                  VirtualizingPanel.CacheLength="2,2"
                  VirtualizingPanel.CacheLengthUnit="Item"
                  ScrollViewer.IsDeferredScrollingEnabled="True"
                  ScrollViewer.CanContentScroll="True"
                  AutoGenerateColumns="False"
                  CanUserAddRows="False">
            <DataGrid.Columns>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Grid Width="{Binding DataContext.GridWidth,RelativeSource={RelativeSource AncestorType=Window}}"
                                  Height="{Binding DataContext.GridHeight,RelativeSource={RelativeSource AncestorType=Window}}"
                                  >
                                <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="FontSize" Value="50"/>
                                                <Setter Property="Foreground" Value="Red"/>
                                            </Trigger>
                                        </Style.Triggers>
                                    </Style>
                                </Grid.Resources>
                                <Grid.RowDefinitions>
                                    <RowDefinition/>
                                    <RowDefinition/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition/>
                                    <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 Title}"/>
                                <TextBlock Grid.Row="0" Grid.Column="3" Text="{Binding Topic}"/>
                                <TextBlock Grid.Row="1" Grid.Column="0"  Grid.ColumnSpan="4"
                                           Text="{Binding ISBN}"/>
                            </Grid>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>


using System.Collections.ObjectModel;
using System.Diagnostics;
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 WpfApp39
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.Loaded += async (s, e) =>
            {
                var vm = this.DataContext as MainWindowViewModel;
                if(vm!=null)
                {
                    vm.GridWidth = this.ActualWidth;
                    vm.GridHeight = this.ActualHeight / 2;
                    await vm.InitBooksCollectionAsync();
                }
            };
        }
    }

    public class MainWindowViewModel : BindableBase
    {
        private IIDService idService;
        private INameService nameService;
        private IISBNService isbnService;
        public MainWindowViewModel(IIDService idServiceValue, INameService nameServiceValue,
            IISBNService isbnServiceValue)
        {
            idService = idServiceValue;
            nameService = nameServiceValue;
            isbnService = isbnServiceValue;
        }

        public async Task InitBooksCollectionAsync()
        {
            BooksCollection = new ObservableCollection<Book>();
            List<Book> booksList = new List<Book>();
            for (int i = 1; i < 100000001; i++)
            {
                booksList.Add(new Book()
                {
                    Id=idService.GetID(),
                    Name=nameService.GetName(),
                    ISBN=isbnService.GetISBN(),
                    Title=$"Title_{i}",
                    Topic=$"Topic_{i}"
                });

                if(i%1000000==0)
                {
                    await PopulateBooksCollectionAsync(booksList);
                }
            }
        }

        private async Task PopulateBooksCollectionAsync(List<Book> booksList)
        {
            await Application.Current.Dispatcher.InvokeAsync(() =>
            {
                var tempList = booksList.ToList();
                booksList.Clear();
                foreach (var bk in tempList)
                {
                    BooksCollection.Add(bk);
                }
                MainTitle = $"Loaded {BooksCollection.Count} items,{GetMemory()}";
            }, System.Windows.Threading.DispatcherPriority.Background);
        }

        private string GetMemory()
        {
            var mem = Process.GetCurrentProcess().PrivateMemorySize64 / 1024.0d / 1024.0d;
            return $"Memory:{mem.ToString("N2")} M";
        }

        private string mainTitle;
        public string MainTitle
        {
            get
            {
                return mainTitle; 
            }
            set
            {
                SetProperty(ref  mainTitle, value);
            }
        }

        private double gridWidth;
        public double GridWidth
        {
            get
            {
                return gridWidth;
            }
            set
            {
                SetProperty(ref gridWidth, value);
            }
        }

        private double gridHeight;
        public double GridHeight
        {
            get
            {
                return gridHeight;
            }
            set
            {
                SetProperty(ref gridHeight, value);
            }
        }

        private ObservableCollection<Book> booksCollection;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollection;
            }
            set
            {
                SetProperty(ref booksCollection, value);
            }
        }
    }

    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string ISBN { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }


    #region Interfaces
    public interface IIDService
    {
        int GetID();
    }

    public class IDService : IIDService
    {
        int idx = 0;
        public int GetID()
        {
            return Interlocked.Increment(ref idx);
        }
    }

    public interface INameService
    {
        string GetName();
    }

    public class NameService : INameService
    {
        int idx = 0;
        public string GetName()
        {
            return $"Name_{Interlocked.Increment(ref idx)}";
        }
    }

    public interface IISBNService
    {
        string GetISBN();
    }

    public class ISBNService : IISBNService
    {
        int idx = 0;
        public string GetISBN()
        {
            return $"ISBN_{Interlocked.Increment(ref idx)}";
        }
    }

    #endregion
}

 

 

 

image

 

 

 

 

image

 

 

 

image

 

 

 

image

 

posted @ 2025-10-27 22:18  FredGrit  阅读(1)  评论(0)    收藏  举报