Install-Package Microsoft.Xaml.Behaviors.WPF
public class DataGridAutoScrollIntoViewBehavior:Behavior<DataGrid>
{
ScrollViewer scrollViewer;
private INotifyCollectionChanged _itemsSourceCollection;
private DependencyPropertyDescriptor _itemsSourceDescriptor;
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += AssociatedObject_Loaded;
AssociatedObject.Unloaded += AssociatedObject_Unloaded;
_itemsSourceDescriptor = DependencyPropertyDescriptor.FromProperty(DataGrid.ItemsSourceProperty, typeof(DataGrid));
_itemsSourceDescriptor.AddValueChanged(AssociatedObject, OnItemsSourceChanged);
SubScribeCollectionChanged();
}
protected override void OnDetaching()
{
_itemsSourceDescriptor?.RemoveValueChanged(AssociatedObject, OnItemsSourceChanged);
UnsubscribeCollectionChanged();
base.OnDetaching();
}
private void OnItemsSourceChanged(object? sender, EventArgs e)
{
SubScribeCollectionChanged();
}
private void SubScribeCollectionChanged()
{
UnsubscribeCollectionChanged();
_itemsSourceCollection = AssociatedObject.ItemsSource as INotifyCollectionChanged;
if(_itemsSourceCollection!=null)
{
_itemsSourceCollection.CollectionChanged += _itemsSourceCollection_CollectionChanged;
}
}
private void _itemsSourceCollection_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if(e.Action==NotifyCollectionChangedAction.Add && AssociatedObject.Items.Count%1000000==0)
{
Application.Current?.Dispatcher.Invoke(() =>
{
var lastItem = AssociatedObject.Items[AssociatedObject.Items.Count - 1];
AssociatedObject.ScrollIntoView(lastItem);
},System.Windows.Threading.DispatcherPriority.Background);
}
}
private void UnsubscribeCollectionChanged()
{
if(_itemsSourceCollection!=null)
{
_itemsSourceCollection.CollectionChanged -= _itemsSourceCollection_CollectionChanged;
_itemsSourceCollection = null;
}
}
private void AssociatedObject_Unloaded(object sender, RoutedEventArgs e)
{
UnsubscribeCollectionChanged();
AssociatedObject.Loaded -= AssociatedObject_Loaded;
AssociatedObject.Unloaded -= AssociatedObject_Unloaded;
}
private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
scrollViewer = GetScrollViewer(AssociatedObject);
}
private ScrollViewer GetScrollViewer(DependencyObject dpObj)
{
int cnt = VisualTreeHelper.GetChildrenCount(dpObj);
for(int i=0;i<cnt;i++)
{
var child = VisualTreeHelper.GetChild(dpObj, i);
var scrollViewer = child as ScrollViewer;
if(scrollViewer != null)
{
return scrollViewer;
}
var result = GetScrollViewer(child);
if(result!=null)
{
return result;
}
}
return null;
}
}
//WPF
<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"
xmlns:behavior="http://schemas.microsoft.com/xaml/behaviors"
mc:Ignorable="d"
Title="{Binding MainTitle}" WindowState="Maximized">
<Window.DataContext>
<local:MainVM/>
</Window.DataContext>
<Window.Resources>
<local:ImgUrlToImageSourceConverter x:Key="ImgUrlToImageSourceConverter"/>
<Style TargetType="TextBlock" x:Key="TbkStyle">
<Setter Property="FontSize" Value="30"/>
<Setter Property="HorizontalAlignment" Value="Center"/>
<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,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
IsReadOnly="True"
AutoGenerateColumns="False"
CanUserAddRows="False"
CanUserReorderColumns="False"
VirtualizingPanel.IsVirtualizing="True"
VirtualizingPanel.VirtualizationMode="Recycling"
VirtualizingPanel.CacheLength="5,5"
VirtualizingPanel.CacheLengthUnit="Item"
ScrollViewer.CanContentScroll="True"
ScrollViewer.IsDeferredScrollingEnabled="True"
UseLayoutRounding="True"
SelectionMode="Extended">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Border Width="{x:Static SystemParameters.FullPrimaryScreenWidth}"
Height="{x:Static SystemParameters.FullPrimaryScreenHeight}"
BorderBrush="LightBlue"
BorderThickness="2"
Margin="5">
<Border.Background>
<ImageBrush ImageSource="{Binding ImgUrl,Converter={StaticResource ImgUrlToImageSourceConverter}}"
RenderOptions.BitmapScalingMode="HighQuality"
Stretch="Uniform"/>
</Border.Background>
<Grid>
<Grid.Resources>
<Style TargetType="TextBlock" BasedOn="{StaticResource TbkStyle}"/>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<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 ISBN}" Grid.Row="1" Grid.Column="0"/>
<TextBlock Text="{Binding CategoryName}" Grid.Row="1" Grid.Column="1"/>
<TextBlock Text="{Binding Author}" Grid.Row="2" Grid.Column="0"/>
<TextBlock Text="{Binding Comment}" Grid.Row="2" Grid.Column="1"/>
<TextBlock Text="{Binding Content}" Grid.Row="3" Grid.Column="0"/>
<TextBlock Text="{Binding Summary}" Grid.Row="3" Grid.Column="1"/>
<TextBlock Text="{Binding Title}" Grid.Row="4" Grid.Column="0"/>
<TextBlock Text="{Binding Topic}" Grid.Row="4" Grid.Column="1"/>
</Grid>
</Border>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
<behavior:Interaction.Behaviors>
<local:DataGridAutoScrollIntoViewBehavior/>
</behavior:Interaction.Behaviors>
</DataGrid>
</Grid>
</Window>
using Microsoft.Xaml.Behaviors;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.IO;
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();
Application.Current.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
}
private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
}
private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show(e.Exception.Message);
}
}
public class MainVM : INotifyPropertyChanged
{
private static long id = 1;
private static int interval = 1000000;
private static int batch = 0;
static List<string> imgUrlList = new List<string>();
static int imgsCnt = 0;
List<Book> bksList = new List<Book>(interval);
private static (long, long) GetStartEnd(int cnt = 1000000)
{
long end = Interlocked.Add(ref id, cnt);
long start = end - cnt;
return (start, end);
}
public MainVM()
{
if (!DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
string imgDir = @"../../../Images";
if (Directory.Exists(imgDir))
{
imgUrlList = Directory.GetFiles(imgDir, "*", SearchOption.AllDirectories).ToList();
imgsCnt = imgUrlList.Count;
BksCollection = new ObservableCollection<Book>();
BksCollection.CollectionChanged += BksCollection_CollectionChanged;
try
{
_ = InitBksAsync();
}
catch (Exception ex)
{
MessageBox.Show(ex?.Message);
}
}
else
{
MessageBox.Show($"{System.IO.Path.GetFullPath(imgDir)} does not exist!");
}
}
}
private void BksCollection_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
}
private async Task InitBksAsync(UInt32 cnt = UInt32.MaxValue)
{
int batchCnt = (int)((cnt + interval - 1) / interval);
while (batch < batchCnt)
{
var (start, end) = GetStartEnd(interval);
for (long i = start; i < end; i++)
{
bksList.Add(new Book()
{
Id = i,
Name = $"Name_{i}",
ISBN = $"ISBN_{i}_{Guid.NewGuid():N}",
ImgUrl = $"{imgUrlList[(int)i % imgsCnt]}",
CategoryName = $"Category_{i}",
Author = $"Author_{i}",
Comment = $"Comment_{i}",
Content = $"Content_{i}",
Summary = $"Summary_{i}",
Title = $"Title_{i}",
Topic = $"Topic_{i}"
});
}
await PopulateBksCollectionAsync();
}
}
private async Task PopulateBksCollectionAsync()
{
await Application.Current.Dispatcher.InvokeAsync(() =>
{
var tempList = bksList.ToList();
bksList.Clear();
foreach (var bk in tempList)
{
BksCollection.Add(bk);
}
MainTitle = $"{DateTime.Now},batch:{++batch},FirstId:{BksCollection.FirstOrDefault()?.Id}," +
$"LastId:{BksCollection.LastOrDefault()?.Id},{GetMem()}";
}, System.Windows.Threading.DispatcherPriority.Background);
}
private string GetMem()
{
return $"Memory:{System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64 / 1024 / 1024:N2} M";
}
private ObservableCollection<Book> bksCollection;
public ObservableCollection<Book> BksCollection
{
get
{
return bksCollection;
}
set
{
if (value != bksCollection)
{
bksCollection = value;
OnPropertyChanged();
OnBksCollectionChanged();
}
}
}
private void OnBksCollectionChanged()
{
}
private string mainTitle;
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)
{
return;
}
handler(this, new PropertyChangedEventArgs(propName));
}
}
public class DataGridAutoScrollIntoViewBehavior:Behavior<DataGrid>
{
ScrollViewer scrollViewer;
private INotifyCollectionChanged _itemsSourceCollection;
private DependencyPropertyDescriptor _itemsSourceDescriptor;
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += AssociatedObject_Loaded;
AssociatedObject.Unloaded += AssociatedObject_Unloaded;
_itemsSourceDescriptor = DependencyPropertyDescriptor.FromProperty(DataGrid.ItemsSourceProperty, typeof(DataGrid));
_itemsSourceDescriptor.AddValueChanged(AssociatedObject, OnItemsSourceChanged);
SubScribeCollectionChanged();
}
protected override void OnDetaching()
{
_itemsSourceDescriptor?.RemoveValueChanged(AssociatedObject, OnItemsSourceChanged);
UnsubscribeCollectionChanged();
base.OnDetaching();
}
private void OnItemsSourceChanged(object? sender, EventArgs e)
{
SubScribeCollectionChanged();
}
private void SubScribeCollectionChanged()
{
UnsubscribeCollectionChanged();
_itemsSourceCollection = AssociatedObject.ItemsSource as INotifyCollectionChanged;
if(_itemsSourceCollection!=null)
{
_itemsSourceCollection.CollectionChanged += _itemsSourceCollection_CollectionChanged;
}
}
private void _itemsSourceCollection_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if(e.Action==NotifyCollectionChangedAction.Add && AssociatedObject.Items.Count%1000000==0)
{
Application.Current?.Dispatcher.Invoke(() =>
{
var lastItem = AssociatedObject.Items[AssociatedObject.Items.Count - 1];
AssociatedObject.ScrollIntoView(lastItem);
},System.Windows.Threading.DispatcherPriority.Background);
}
}
private void UnsubscribeCollectionChanged()
{
if(_itemsSourceCollection!=null)
{
_itemsSourceCollection.CollectionChanged -= _itemsSourceCollection_CollectionChanged;
_itemsSourceCollection = null;
}
}
private void AssociatedObject_Unloaded(object sender, RoutedEventArgs e)
{
UnsubscribeCollectionChanged();
AssociatedObject.Loaded -= AssociatedObject_Loaded;
AssociatedObject.Unloaded -= AssociatedObject_Unloaded;
}
private void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
scrollViewer = GetScrollViewer(AssociatedObject);
}
private ScrollViewer GetScrollViewer(DependencyObject dpObj)
{
int cnt = VisualTreeHelper.GetChildrenCount(dpObj);
for(int i=0;i<cnt;i++)
{
var child = VisualTreeHelper.GetChild(dpObj, i);
var scrollViewer = child as ScrollViewer;
if(scrollViewer != null)
{
return scrollViewer;
}
var result = GetScrollViewer(child);
if(result!=null)
{
return result;
}
}
return null;
}
}
public class Book
{
public long Id { get; set; }
public string ImgUrl { get; set; }
public string ISBN { get; set; }
public string Name { get; set; }
public string CategoryName { 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 class ImgUrlToImageSourceConverter : IValueConverter
{
private static Dictionary<string, ImageSource> imgCache = new Dictionary<string, ImageSource>();
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var url = value?.ToString();
if (!File.Exists(url))
{
return null;
}
if (imgCache.TryGetValue(url, out ImageSource imgSource))
{
return imgSource;
}
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri(url, UriKind.RelativeOrAbsolute);
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();
if (bmp.CanFreeze)
{
bmp.Freeze();
}
imgCache.TryAdd(url, bmp);
return bmp;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
![image]()
![image]()