Skip to content

Commit 56ac897

Browse files
authored
Merge pull request #282 from AvaloniaUI/fixes/selection-model-enumerable
Fix incorrect cast in TreeSelectionModelBase
2 parents c7c178c + 8ac8653 commit 56ac897

File tree

1 file changed

+44
-6
lines changed

1 file changed

+44
-6
lines changed

src/Avalonia.Controls.TreeDataGrid/Selection/TreeSelectionModelBase.cs

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,7 @@ public bool IsSelected(IndexPath index)
204204

205205
protected virtual bool TryGetItemAt(IndexPath index, out T? result)
206206
{
207-
var items = (IReadOnlyList<T>?)_root.ItemsView;
207+
var items = (IEnumerable<T>?)_root.ItemsView;
208208
var count = index.Count;
209209

210210
for (var i = 0; i < count; ++i)
@@ -215,17 +215,21 @@ protected virtual bool TryGetItemAt(IndexPath index, out T? result)
215215
return false;
216216
}
217217

218-
var j = index[i];
219-
220-
if (j < items.Count)
218+
if (TryGetElementAt(items, index[i], out var item))
221219
{
222220
if (i == count - 1)
223221
{
224-
result = items[j];
222+
result = item;
225223
return true;
226224
}
227225
else
228-
items = GetChildren(items[j]) as IReadOnlyList<T>;
226+
{
227+
items = GetChildren(item);
228+
}
229+
}
230+
else
231+
{
232+
break;
229233
}
230234
}
231235

@@ -566,6 +570,40 @@ internal static bool ShiftIndex(IndexPath parentIndex, int shiftIndex, int shift
566570
return false;
567571
}
568572

573+
private static bool TryGetElementAt(IEnumerable<T> items, int index, [MaybeNullWhen(false)] out T result)
574+
{
575+
if (items is IList<T> list)
576+
{
577+
if (index < list.Count)
578+
{
579+
result = list[index];
580+
return true;
581+
}
582+
}
583+
else if (items is IReadOnlyList<T> ro)
584+
{
585+
if (index < ro.Count)
586+
{
587+
result = ro[index];
588+
return true;
589+
}
590+
}
591+
else
592+
{
593+
foreach (var item in items)
594+
{
595+
if (index-- == 0)
596+
{
597+
result = item;
598+
return true;
599+
}
600+
}
601+
}
602+
603+
result = default;
604+
return false;
605+
}
606+
569607
public struct BatchUpdateOperation : IDisposable
570608
{
571609
private readonly TreeSelectionModelBase<T> _owner;

0 commit comments

Comments
 (0)