Skip to content

Commit

Permalink
Merge pull request #146 from symbiogenesis/observablerangecollection
Browse files Browse the repository at this point in the history
Use ObservableRangeCollection from MvvmHelpers to reduce allocations
  • Loading branch information
symbiogenesis authored Dec 29, 2023
2 parents 4336672 + 9ad1877 commit d22ee5a
Show file tree
Hide file tree
Showing 3 changed files with 225 additions and 9 deletions.
17 changes: 8 additions & 9 deletions Maui.DataGrid/DataGrid.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace Maui.DataGrid;
using System.Diagnostics;
using System.Windows.Input;
using Maui.DataGrid.Extensions;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.Shapes;
using Font = Microsoft.Maui.Font;

Expand Down Expand Up @@ -36,7 +37,6 @@ public partial class DataGrid

private readonly object _reloadLock = new();
private readonly object _sortAndPaginateLock = new();
private IList<object>? _internalItems;
private DataGridColumn? _sortedColumn;

#endregion Fields
Expand All @@ -49,6 +49,7 @@ public partial class DataGrid
public DataGrid()
{
InitializeComponent();
_collectionView.ItemsSource = InternalItems;
_defaultHeaderStyle = (Style)Resources["DefaultHeaderStyle"];
_defaultSortIconStyle = (Style)Resources["DefaultSortIconStyle"];
}
Expand Down Expand Up @@ -230,11 +231,12 @@ private void SortAndPaginate(SortData? sortData = null)

if (PaginationEnabled)
{
InternalItems = GetPaginatedItems(sortedItems).ToList();
var paginatedItems = GetPaginatedItems(sortedItems);
InternalItems.ReplaceRange(paginatedItems);
}
else
{
InternalItems = sortedItems;
InternalItems.ReplaceRange(sortedItems);
}
}
}
Expand Down Expand Up @@ -542,7 +544,7 @@ private void SortAndPaginate(SortData? sortData = null)
throw new InvalidOperationException("DataGrid must have SelectionEnabled=true to set SelectedItem");
}

if (self.InternalItems?.Contains(v) == true)
if (self.InternalItems.Contains(v))
{
return v;
}
Expand Down Expand Up @@ -1063,6 +1065,8 @@ private set

#pragma warning restore CA2227 // Collection properties should be read only

internal ObservableRangeCollection<object> InternalItems { get; } = [];

#endregion Properties

#region UI Methods
Expand Down Expand Up @@ -1179,11 +1183,6 @@ internal void Reload()
UpdatePageSizeList();

InitHeaderView();

if (_internalItems is not null)
{
InternalItems = new List<object>(_internalItems);
}
}
}

Expand Down
7 changes: 7 additions & 0 deletions Maui.DataGrid/DataGridRow.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,13 @@ public object RowToEdit
if (o is DataGrid oldDataGrid)
{
oldDataGrid.ItemSelected -= self.DataGrid_ItemSelected;
oldDataGrid.Columns.CollectionChanged += self.OnColumnsChanged;
}

if (n is DataGrid newDataGrid && newDataGrid.SelectionEnabled)
{
newDataGrid.ItemSelected += self.DataGrid_ItemSelected;
newDataGrid.Columns.CollectionChanged += self.OnColumnsChanged;
}
});

Expand Down Expand Up @@ -383,6 +385,11 @@ protected override void OnParentSet()
}
}

private void OnColumnsChanged(object? sender, EventArgs e)
{
CreateView();
}

private void DataGrid_ItemSelected(object? sender, SelectionChangedEventArgs e)
{
if (!DataGrid.SelectionEnabled)
Expand Down
210 changes: 210 additions & 0 deletions Maui.DataGrid/ObservableRangeCollection.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
/*-----------------------------------------------------------------------
<copyright file="ObservableRangeCollection.cs">
The MIT License (MIT)
Copyright (c) 2017 James Montemagno
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---------------------------------
This project also uses the following.
---------------------------------
MIT License
Copyright (c) 2018 Brandon Minnick (https://github.com/brminnick/AsyncAwaitBestPractices)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---------------------------------
Xamarin SDK (https://github.com/xamarin/Xamarin.Forms/)
The MIT License (MIT)
Copyright (c) .NET Foundation Contributors
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
</copyright>
-----------------------------------------------------------------------*/
namespace Maui.DataGrid;

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;

/// <summary>
/// Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.
/// </summary>
/// <typeparam name="T">The object type of elements in the collection.</typeparam>
internal sealed class ObservableRangeCollection<T> : ObservableCollection<T>
{
/// <summary>
/// Initializes a new instance of the <see cref="ObservableRangeCollection{T}"/> class.
/// </summary>
public ObservableRangeCollection()
{
}

/// <summary>
/// Initializes a new instance of the <see cref="ObservableRangeCollection{T}"/> class that contains elements copied from the specified collection.
/// </summary>
/// <param name="collection">collection: The collection from which the elements are copied.</param>
/// <exception cref="ArgumentNullException">The collection parameter cannot be null.</exception>
public ObservableRangeCollection(IEnumerable<T> collection)
: base(collection)
{
}

/// <summary>
/// Adds the elements of the specified collection to the end of the ObservableCollection(Of T).
/// </summary>
/// <param name="collection">The collection to add.</param>
/// <param name="notificationMode">The notification mode.</param>
/// <exception cref="ArgumentException">An exception when an invalid notification mode is set.</exception>
public void AddRange(IEnumerable<T> collection, NotifyCollectionChangedAction notificationMode = NotifyCollectionChangedAction.Add)
{
if (notificationMode is not NotifyCollectionChangedAction.Add and not NotifyCollectionChangedAction.Reset)
{
throw new ArgumentException("Mode must be either Add or Reset for AddRange.", nameof(notificationMode));
}

ArgumentNullException.ThrowIfNull(collection);

CheckReentrancy();

var startIndex = Count;

var itemsAdded = AddArrangeCore(collection);

if (!itemsAdded)
{
return;
}

if (notificationMode == NotifyCollectionChangedAction.Reset)
{
RaiseChangeNotificationEvents(action: NotifyCollectionChangedAction.Reset);

return;
}

var changedItems = collection is List<T> list ? list : new List<T>(collection);

RaiseChangeNotificationEvents(
action: NotifyCollectionChangedAction.Add,
changedItems: changedItems,
startingIndex: startIndex);
}

/// <summary>
/// Removes the first occurrence of each item in the specified collection from ObservableCollection(Of T). NOTE: with notificationMode = Remove, removed items starting index is not set because items are not guaranteed to be consecutive.
/// </summary>
/// <param name="collection">The collection to remove.</param>
/// <param name="notificationMode">The notification mode.</param>
/// <exception cref="ArgumentException">An exception when an invalid notification mode is set.</exception>
public void RemoveRange(IEnumerable<T> collection, NotifyCollectionChangedAction notificationMode = NotifyCollectionChangedAction.Reset)
{
if (notificationMode is not NotifyCollectionChangedAction.Remove and not NotifyCollectionChangedAction.Reset)
{
throw new ArgumentException("Mode must be either Remove or Reset for RemoveRange.", nameof(notificationMode));
}

ArgumentNullException.ThrowIfNull(collection);

CheckReentrancy();

if (notificationMode == NotifyCollectionChangedAction.Reset)
{
var raiseEvents = false;
foreach (var item in collection)
{
_ = Items.Remove(item);
raiseEvents = true;
}

if (raiseEvents)
{
RaiseChangeNotificationEvents(action: NotifyCollectionChangedAction.Reset);
}

return;
}

var changedItems = new List<T>(collection);
for (var i = 0; i < changedItems.Count; i++)
{
if (!Items.Remove(changedItems[i]))
{
changedItems.RemoveAt(i); // Can't use a foreach because changedItems is intended to be (carefully) modified
i--;
}
}

if (changedItems.Count == 0)
{
return;
}

RaiseChangeNotificationEvents(
action: NotifyCollectionChangedAction.Remove,
changedItems: changedItems);
}

/// <summary>
/// Clears the current collection and replaces it with the specified item.
/// </summary>
/// <param name="item">The item to replace the collection with.</param>
public void Replace(T item) => ReplaceRange(new T[] { item });

/// <summary>
/// Clears the current collection and replaces it with the specified collection.
/// </summary>
/// <param name="collection">The collection to replace with.</param>
public void ReplaceRange(IEnumerable<T> collection)
{
ArgumentNullException.ThrowIfNull(collection);

CheckReentrancy();

var previouslyEmpty = Items.Count == 0;

Items.Clear();

_ = AddArrangeCore(collection);

var currentlyEmpty = Items.Count == 0;

if (previouslyEmpty && currentlyEmpty)
{
return;
}

RaiseChangeNotificationEvents(action: NotifyCollectionChangedAction.Reset);
}

private bool AddArrangeCore(IEnumerable<T> collection)
{
var itemAdded = false;
foreach (var item in collection)
{
Items.Add(item);
itemAdded = true;
}

return itemAdded;
}

private void RaiseChangeNotificationEvents(NotifyCollectionChangedAction action, List<T>? changedItems = null, int startingIndex = -1)
{
OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));

if (changedItems is null)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action));
}
else
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(action, changedItems: changedItems, startingIndex: startingIndex));
}
}
}

0 comments on commit d22ee5a

Please sign in to comment.