Skip to content

Commit b9a0236

Browse files
authored
Merge pull request #190 from EVEJay/master
Refactored to use pooling
2 parents 242e6f5 + 601aabf commit b9a0236

File tree

3 files changed

+198
-37
lines changed

3 files changed

+198
-37
lines changed

SMT/Helpers/CanvasExtensions.cs

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
using System.Collections.Generic;
2+
using System.Linq;
3+
using System.Windows;
4+
using System.Windows.Controls;
5+
using System.Windows.Shapes;
6+
7+
namespace SMT.Helpers;
8+
9+
public static class CanvasExtensions
10+
{
11+
public static void EnsureChild(this Canvas canvas, UIElement element)
12+
{
13+
if (element == null) return;
14+
if (!canvas.Children.Contains(element))
15+
{
16+
canvas.Children.Add(element);
17+
}
18+
}
19+
20+
public static void ClearChildren(this Canvas canvas, IList<UIElement> elements)
21+
{
22+
if (elements == null) return;
23+
foreach (UIElement childElement in elements.ToList())
24+
{
25+
if (canvas.Children.Contains(childElement))
26+
{
27+
canvas.Children.Remove(childElement);
28+
}
29+
}
30+
elements.Clear();
31+
}
32+
33+
public static void ReleaseChildren<T>(this Canvas canvas, IList<T> elements, ElementPool<T> pool) where T : Shape, new()
34+
{
35+
if (elements == null) return;
36+
foreach (T element in elements.ToList())
37+
{
38+
pool.Release(canvas, element);
39+
}
40+
elements.Clear();
41+
}
42+
43+
}

SMT/Helpers/ElementPool.cs

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
using System.Collections.Generic;
2+
using System.Windows;
3+
using System.Windows.Controls;
4+
5+
namespace SMT.Helpers;
6+
7+
/// <summary>
8+
/// Simple Element pool for reusable UI Elements.
9+
/// </summary>
10+
/// <typeparam name="T">The pooled elements type, must be (derived from) Shape.</typeparam>
11+
public class ElementPool<T> where T : UIElement, new()
12+
{
13+
private readonly Stack<T> _pool = new();
14+
15+
/// <summary>
16+
/// Get an element out of the pool or create a new one
17+
/// if there is none left.
18+
/// </summary>
19+
/// <returns>An element of the desired type.</returns>
20+
public T Get()
21+
{
22+
if (_pool.Count > 0)
23+
{
24+
T item = _pool.Pop();
25+
item.Visibility = Visibility.Visible;
26+
return item;
27+
}
28+
29+
return new T();
30+
}
31+
32+
/// <summary>
33+
/// Hides and element, removes it from the canvas and
34+
/// returns it to the pool.
35+
/// </summary>
36+
/// <param name="canvas"></param>
37+
/// <param name="item"></param>
38+
public void Release(Canvas canvas, T item)
39+
{
40+
if (item == null) return;
41+
item.Visibility = Visibility.Collapsed;
42+
if (canvas.Children.Contains(item))
43+
{
44+
canvas.Children.Remove(item);
45+
}
46+
_pool.Push(item);
47+
}
48+
}

0 commit comments

Comments
 (0)