From 1c01de002b58bd2249f66fcb5738de7dacb4ee45 Mon Sep 17 00:00:00 2001 From: xiaoy312 Date: Thu, 16 Jan 2025 19:01:25 -0500 Subject: [PATCH] fix: align DepObjCol indexer behavior with winui (cherry picked from commit 3268696bb277457bab67cea222a9e551a447b3eb) --- .../Given_DependencyObjectCollection.cs | 15 ++++++++++++++- src/Uno.UI/UI/Xaml/DependencyObjectCollection.cs | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_DependencyObjectCollection.cs b/src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_DependencyObjectCollection.cs index 2ea54933aa30..1814b458e3f5 100644 --- a/src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_DependencyObjectCollection.cs +++ b/src/Uno.UI.RuntimeTests/Tests/Windows_UI_Xaml/Given_DependencyObjectCollection.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices.ObjectiveC; using Microsoft.UI.Xaml; @@ -28,4 +29,16 @@ public void When_Add_Multiple_And_Invoke() Assert.IsTrue(list.SequenceEqual(["One", "Two"])); } + + [TestMethod] + public void When_Indexer_Get_IndexOutOfRange() + { + Assert.IsNull(new DependencyObjectCollection()[int.MaxValue]); + } + + [TestMethod] + public void When_Indexer_Get_NegativeIndex() + { + Assert.ThrowsException(() => new DependencyObjectCollection()[-1]); + } } diff --git a/src/Uno.UI/UI/Xaml/DependencyObjectCollection.cs b/src/Uno.UI/UI/Xaml/DependencyObjectCollection.cs index 976cef393567..8bd44c87f500 100644 --- a/src/Uno.UI/UI/Xaml/DependencyObjectCollection.cs +++ b/src/Uno.UI/UI/Xaml/DependencyObjectCollection.cs @@ -127,7 +127,7 @@ private protected virtual void ValidateItem(T item) { } public T this[int index] { - get => _list[index]; + get => index < _list.Count ? _list[index] : default; set { ValidateItem(value);