public void Test_ObservableCollection_Remove()
        {
            var list = new ObservableCollection<int>() { 4, 5, 6 };
            Assert.Equal(3, list.Count);
            list.Remove(4);
            Assert.Equal(2, list.Count);
            Assert.DoesNotContain(4, list);
            var collection = list as ICollection<int>;
            Assert.NotNull(collection);
            Assert.True(collection.Remove(5));
            Assert.Equal(1, collection.Count);
            Assert.DoesNotContain(5, list);

            list = new ObservableCollection<int>() { 4, 5, 6 };
            list.CollectionChanged += (o, e) =>
            {
                Assert.Same(list, o);
                Assert.Equal(NotifyCollectionChangedAction.Remove, e.Action);
                Assert.Null(e.NewItems);
                Assert.NotNull(e.OldItems);
                Assert.Equal(1, e.OldItems.Count);
                Assert.Equal(5, e.OldItems[0]);
            };
            list.RemoveAt(1);
            Assert.Equal(2, list.Count);
            Assert.DoesNotContain(5, list);
        }
    static void Main()
    {
        ObservableCollection<string> items = new ObservableCollection<string>();
        items.CollectionChanged += items_CollectionChanged;

        items.Add("new item");
        items.Add("another item");
        items.Add("one more item");
        items[1] = "new value";
        items.RemoveAt(0);
    }
        /// <summary>
        /// Verifies that the item is removed from a given index in the collection.
        /// </summary>
        public void RemoveItemAtTest(ReadOnlyObservableCollection<string> readOnlyCol, ObservableCollection<string> collection,
            int itemIndex)
        {
            INotifyPropertyChanged readOnlyPropertyChanged = readOnlyCol;
            readOnlyPropertyChanged.PropertyChanged += Collection_PropertyChanged;
            _expectedPropertyChanged = new[]
            {
                new PropertyNameExpected(COUNT),
                new PropertyNameExpected(ITEMARRAY)
            };

            INotifyCollectionChanged readOnlyCollectionChange = readOnlyCol;
            readOnlyCollectionChange.CollectionChanged += Collection_CollectionChanged;

            string itemAtOldIndex = collection[itemIndex];

            _expectedCollectionChangedFired++;
            _expectedAction = NotifyCollectionChangedAction.Remove;
            _expectedNewItems = null;
            _expectedNewStartingIndex = -1;
            _expectedOldItems = new string[] { itemAtOldIndex };
            _expectedOldStartingIndex = itemIndex;

            int expectedCount = collection.Count - 1;

            collection.RemoveAt(itemIndex);
            Assert.Equal(expectedCount, readOnlyCol.Count);
            Assert.Equal(_expectedCollectionChangedFired, _numCollectionChangedFired);

            foreach (var item in _expectedPropertyChanged)
                Assert.True(item.IsFound, "The propertychanged event should have fired for" + item.Name + ", since we replaced an item");

            readOnlyCollectionChange.CollectionChanged -= Collection_CollectionChanged;
            readOnlyPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
        }
        public static void RemoveAtTest_Negative()
        {
            Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
            ObservableCollection<Guid> collection = new ObservableCollection<Guid>(anArray);
            ReadOnlyObservableCollection<Guid> readonlyCol = new ReadOnlyObservableCollection<Guid>(collection);
            ((INotifyCollectionChanged)readonlyCol).CollectionChanged += (o, e) => { throw new ShouldNotBeInvokedException(); };

            int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
            foreach (var index in iArrInvalidValues)
            {
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(index));
                Assert.Equal(anArray.Length, readonlyCol.Count);
            }

            int[] iArrLargeValues = new Int32[] { collection.Count, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
            foreach (var index in iArrLargeValues)
            {
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(index));
                Assert.Equal(anArray.Length, readonlyCol.Count);
            }
        }
        public static void RemoveAtTest_Negative()
        {
            Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
            ObservableCollection<Guid> collection = new ObservableCollection<Guid>(anArray);
            collection.CollectionChanged += (o, e) =>
            {
                Assert.True(false, "Should not have thrown collection changed event when removing items from invalid indices");
            };

            int[] iArrInvalidValues = new Int32[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, Int32.MinValue };
            foreach (var index in iArrInvalidValues)
            {
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(index));
                Assert.Equal(anArray.Length, collection.Count);
            }

            int[] iArrLargeValues = new Int32[] { collection.Count, Int32.MaxValue, Int32.MaxValue / 2, Int32.MaxValue / 10 };
            foreach (var index in iArrLargeValues)
            {
                Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(index));
                Assert.Equal(anArray.Length, collection.Count);
            }
        }
        public static void RemoveAtTest()
        {
            Guid[] anArray = { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() };
            ObservableCollection<Guid> col0 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
            ObservableCollection<Guid> col1 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);
            ObservableCollection<Guid> col2 = new ObservableCollection<Guid>((IEnumerable<Guid>)anArray);

            col0.RemoveAt(0);
            string collectionString = "";
            foreach (var item in col1)
                collectionString += item + ", ";
            Assert.False(col0.Contains(anArray[0]), "Collection0 should no longer contain the item: " + anArray[0] + " Collection: " + collectionString);

            col1.RemoveAt(1);
            collectionString = "";
            foreach (var item in col1)
                collectionString += item + ", ";
            Assert.False(col1.Contains(anArray[1]), "Collection1 should no longer contain the item: " + anArray[1] + " Collection: " + collectionString);

            col2.RemoveAt(2);
            collectionString = "";
            foreach (var item in col2)
                collectionString += item + ", ";
            Assert.False(col2.Contains(anArray[2]), "Collection2 should no longer contain the item: " + anArray[2] + " Collection: " + collectionString);

            string[] anArrayString = { "one", "two", "three", "four" };
            ObservableCollection<string> col = new ObservableCollection<string>(anArrayString);
            CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
            helper.RemoveItemAtTest(col, 1);
        }
        public async Task OnRemoveNotifyCollectionChangedThenIndexProvided()
        {
            await ExecuteOnUIThread(() =>
                {
                    var originalCollection = new ObservableCollection<ItemMetadata>();
                    originalCollection.Add(new ItemMetadata("a"));
                    originalCollection.Add(new ItemMetadata("b"));
                    originalCollection.Add(new ItemMetadata("c"));
                    IViewsCollection viewsCollection = new ViewsCollection(originalCollection, (i) => true);

                    var eventTracker = new CollectionChangedTracker(viewsCollection);
                    originalCollection.RemoveAt(1);

                    var removeEvent = eventTracker.NotifyEvents.Single(e => e.Action == NotifyCollectionChangedAction.Remove);
                    Assert.IsNotNull(removeEvent);
                    Assert.AreEqual(1, removeEvent.OldStartingIndex);
                });
        }
 /// <summary>
 /// Removes a set of tracks from a given collection of tracks.
 /// </summary>
 /// <param name="tracksToRemove">The tracks to remove</param>
 /// <param name="tracks">The collection from where to remove the tracks</param>
 /// <param name="progressDelta">The amount to increase the scanner progressbar for total scan</param>
 private void RemoveTracks(SortedList<string, TrackData> tracksToRemove, ObservableCollection<TrackData> tracks, double progressDelta = -1)
 {
     //double progress = 0;
     //double trackDelta = 0;
     //if (progressDelta > 0)
     //{
     //    Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
     //    {
     //        trackDelta = progressDelta / tracks.Count;
     //        progress = ScanProgressBar.Value;
     //    }));
     //}
     for (int i = 0, j=0; i < tracks.Count; i++,j++)
     {
         if (tracksToRemove.ContainsKey(tracks[i].Path))
         {
             Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
             {
                 tracks.RemoveAt(i--);
             }));
         }
         //if (progressDelta > 0)
         //{
         //    if (j % 100 == 0 || (int)progress % 10 == 0)
         //        Dispatcher.Invoke(DispatcherPriority.Background, new Action(delegate()
         //        {
         //            ScanProgressBar.Value += progressDelta;
         //        }));
         //    progress += trackDelta;
         //}
     }
 }
        /// <summary>
        /// Checks the object validation for fields warnings or errors.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="propertyChanged">The property changed.</param>
        /// <param name="infoList">The info list containing the warning or error info.</param>
        /// <param name="validationType">Type of the validation.</param>
        private static void CheckObjectValidationForFields(object value, string propertyChanged, ObservableCollection<FieldWarningOrErrorInfo> infoList,
            ValidationType validationType)
        {
            if (string.IsNullOrEmpty(propertyChanged))
            {
                infoList.Clear();
            }
            else
            {
                for (int i = 0; i < infoList.Count; i++)
                {
                    if (string.Compare(infoList[i].Field, propertyChanged) == 0)
                    {
                        infoList.RemoveAt(i);
                    }
                }
            }

            Dictionary<string, string> fieldWarningsOrErrors = CheckFieldWarningsOrErrors(value, propertyChanged, validationType);
            foreach (var fieldWarningOrError in fieldWarningsOrErrors)
            {
                var fieldWarningOrErrorInfo = new FieldWarningOrErrorInfo(fieldWarningOrError.Key, fieldWarningOrError.Value);
                if (!infoList.Contains(fieldWarningOrErrorInfo))
                {
                    infoList.Add(new FieldWarningOrErrorInfo(fieldWarningOrError.Key, fieldWarningOrError.Value));
                }
            }
        }
 private void UpdateUnconsumedProperties(CategoryEditor newEditor, ObservableCollection<PropertyEntry> unconsumedProperties)
 {
     for (int i = unconsumedProperties.Count - 1; i >= 0; i--)
     {
         if (newEditor.ConsumesProperty(unconsumedProperties[i]))
         {
             unconsumedProperties.RemoveAt(i);
         }
     }
 }
        public void SetItemsSourceAndModifyCollection()
        {
            // Create the DataGrid and setup its binding
            ObservableCollection<string> strings = new ObservableCollection<string>() { "one", "two", "three" };
            bool isLoaded = false;
            DataGrid dataGrid = new DataGrid();
            dataGrid.Loaded += delegate { isLoaded = true; };

            // Set the ItemsSource and verify the slot counts
            dataGrid.ItemsSource = strings;
            dataGrid.SelectedIndex = 0;
            Assert.AreEqual(3, dataGrid.SlotCount, "Incorrect SlotCount after setting ItemsSource");
            Assert.AreEqual(3, dataGrid.VisibleSlotCount, "Incorrect VisibleSlotCount after setting ItemsSource");
            Assert.AreEqual(0, dataGrid.SelectedIndex, "SelectedIndex incorrect");

            // Remove an item and verify that the DataGrid is updated
            strings.RemoveAt(1);
            Assert.AreEqual(2, dataGrid.SlotCount, "Incorrect SlotCount after removing an item");
            Assert.AreEqual(2, dataGrid.VisibleSlotCount, "Incorrect VisibleSlotCount after removing an item");
            Assert.AreEqual(0, dataGrid.SelectedIndex, "SelectedIndex incorrect after removing an item");

            // Add an item and verify that the DataGrid is updated
            strings.Add("four");
            Assert.AreEqual(3, dataGrid.SlotCount, "Incorrect SlotCount after adding an item");
            Assert.AreEqual(3, dataGrid.VisibleSlotCount, "Incorrect VisibleSlotCount after adding an item");
            Assert.AreEqual(0, dataGrid.SelectedIndex, "SelectedIndex incorrect after adding an item");

            // Insert an item an dverify that the DataGrid is updated
            strings.Insert(0, "zero");
            Assert.AreEqual(4, dataGrid.SlotCount, "Incorrect SlotCount after inserting an item");
            Assert.AreEqual(4, dataGrid.VisibleSlotCount, "Incorrect VisibleSlotCount after inserting an item");
            Assert.AreEqual(1, dataGrid.SelectedIndex, "SelectedIndex incorrect after inserting an item");

            // Add the DataGrid to the visual tree
            TestPanel.Children.Add(dataGrid);
            this.EnqueueConditional(delegate { return isLoaded; });

            this.EnqueueYieldThread();
            this.EnqueueCallback(delegate
            {
                Assert.AreEqual(4, dataGrid.SlotCount, "Incorrect SlotCount after adding and removing items");
                Assert.AreEqual(4, dataGrid.VisibleSlotCount, "Incorrect VisibleSlotCount after adding and removing items");
                Assert.AreEqual(1, dataGrid.SelectedIndex, "SelectedIndex was not updated when collection changed");
                Assert.AreEqual("one", dataGrid.SelectedItem, "SelectedItem was not updated when collection changed");

                DataGridRow row = dataGrid.DisplayData.GetDisplayedRow(0);
                Assert.IsNotNull(row);
                Assert.AreEqual(0, row.Slot, "Incorrect Row.Slot");
                Assert.AreEqual(0, row.Index, "Incorrect Row.Index");
                Assert.AreEqual("zero", row.DataContext, "Incorrect Row.DataContext");

                row = dataGrid.DisplayData.GetDisplayedRow(1);
                Assert.IsNotNull(row);
                Assert.AreEqual(1, row.Slot, "Incorrect Row.Slot");
                Assert.AreEqual(1, row.Index, "Incorrect Row.Index");
                Assert.AreEqual("one", row.DataContext, "Incorrect Row.DataContext");

                row = dataGrid.DisplayData.GetDisplayedRow(2);
                Assert.IsNotNull(row);
                Assert.AreEqual(2, row.Slot, "Incorrect Row.Slot");
                Assert.AreEqual(2, row.Index, "Incorrect Row.Index");
                Assert.AreEqual("three", row.DataContext, "Incorrect Row.DataContext");

                row = dataGrid.DisplayData.GetDisplayedRow(3);
                Assert.IsNotNull(row);
                Assert.AreEqual(3, row.Slot, "Incorrect Row.Slot");
                Assert.AreEqual(3, row.Index, "Incorrect Row.Index");
                Assert.AreEqual("four", row.DataContext, "Incorrect Row.DataContext");
            });
            this.EnqueueTestComplete();
        }
Exemple #12
0
        // keep inner and outer CollViews' GroupDescription collections in synch 
        private void SynchronizeGroupDescriptions(NotifyCollectionChangedEventArgs e, ObservableCollection<GroupDescription> origin, ObservableCollection<GroupDescription> clone)
        { 
            if (clone == null)
                return;             // the clone might be lazily-created _groupBy

            int i; 

            switch (e.Action) 
            { 
                case NotifyCollectionChangedAction.Add:
                    Debug.Assert(e.NewStartingIndex >= 0); 
                    if (clone.Count + e.NewItems.Count != origin.Count)
                        goto case NotifyCollectionChangedAction.Reset;
                    for (i = 0; i < e.NewItems.Count; i++)
                    { 
                        clone.Insert(e.NewStartingIndex + i, (GroupDescription) e.NewItems[i]);
                    } 
                    break; 

                case NotifyCollectionChangedAction.Remove: 
                    Debug.Assert(e.OldStartingIndex >= 0);
                    if (clone.Count - e.OldItems.Count != origin.Count)
                        goto case NotifyCollectionChangedAction.Reset;
                    for (i = 0; i < e.OldItems.Count; i++) 
                    {
                        clone.RemoveAt(e.OldStartingIndex); 
                    } 
                    break;
 
                case NotifyCollectionChangedAction.Replace:
                    Debug.Assert(e.OldStartingIndex >= 0);
                    if (clone.Count + e.NewItems.Count - e.OldItems.Count != origin.Count)
                        goto case NotifyCollectionChangedAction.Reset; 
                    // If there are as many new items as old items, then
                    // this is a straight replace. 
                    if (e.OldItems.Count == e.NewItems.Count) 
                    {
                        for (i = 0; i < e.OldItems.Count; i++) 
                        {
                            clone[e.OldStartingIndex + i] = (GroupDescription) e.NewItems[i];
                        }
                    } 
                    else
                    { 
                        for (i = 0; i < e.OldItems.Count; i++) 
                        {
                            clone.RemoveAt(e.OldStartingIndex); 
                        }
                        for (i = 0; i < e.NewItems.Count; i++)
                        {
                            clone.Insert(e.NewStartingIndex + i, (GroupDescription) e.NewItems[i]); 
                        }
                    } 
                    break; 

                case NotifyCollectionChangedAction.Move: 
                    Debug.Assert(e.OldStartingIndex >= 0);
                    if (clone.Count != origin.Count)
                        goto case NotifyCollectionChangedAction.Reset;
                    if (e.OldItems.Count == 1) 
                    {
                        clone.Move(e.OldStartingIndex, e.NewStartingIndex); 
                    } 
                    else
                    { 
                        if (e.NewStartingIndex < e.OldStartingIndex)
                        {
                            for (i = 0; i < e.OldItems.Count; i++)
                            { 
                                clone.Move(e.OldStartingIndex + i, e.NewStartingIndex + i);
                            } 
                        } 
                        else if (e.NewStartingIndex > e.OldStartingIndex)
                        { 
                            for (i = e.OldItems.Count - 1; i >= 0; i--)
                            {
                                clone.Move(e.OldStartingIndex + i, e.NewStartingIndex + i);
                            } 
                        }
                    } 
                    break; 

                // this arm also handles cases where the two collections have gotten 
                // out of [....] (typically because exceptions prevented a previous [....]
                // from happening)
                case NotifyCollectionChangedAction.Reset:
                    CloneList(clone, origin); 
                    break;
                default: 
                    throw new NotSupportedException(SR.Get(SRID.UnexpectedCollectionChangeAction, e.Action)); 
            }
        } 
Exemple #13
0
        //ObservableCollectionTest
        public static void ObservableCollectionTest()
        {
            var data = new ObservableCollection<string>();

            data.CollectionChanged += new NotifyCollectionChangedEventHandler(DataCollectionChanged);

            data.Add("One");
            data.Add("Two");
            data.Add("Three");
            data.Insert(1,"$^^$");
            data.RemoveAt(1);
            foreach (var tmp in data)
            {
                Console.WriteLine(tmp);
            }
        }
        public void OnRemoveOfFilterMatchingItemThenViewCollectionRelativeIndexProvided()
        {
            var originalCollection = new ObservableCollection<ItemMetadata>();
            originalCollection.Add(new ItemMetadata("a"));
            originalCollection.Add(new ItemMetadata("b"));
            originalCollection.Add(new ItemMetadata("c"));
            IViewsCollection viewsCollection = new ViewsCollection(originalCollection, (i) => !"b".Equals(i.Item));

            var eventTracker = new CollectionChangedTracker(viewsCollection);
            originalCollection.RemoveAt(2);

            var removeEvent = eventTracker.NotifyEvents.Single(e => e.Action == NotifyCollectionChangedAction.Remove);
            Assert.IsNotNull(removeEvent);
            Assert.AreEqual(1, removeEvent.OldStartingIndex);
        }
 /// <summary>
 /// Removes tracks with a given filename for a specific collection of tracks
 /// </summary>
 /// <param name="filename">The filename of the tracks to remove</param>
 /// <param name="tracks">The collection of tracks from which to remove</param>
 private void RemoveTrack(String filename, ObservableCollection<TrackData> tracks)
 {
     for (int i = 0; i < tracks.Count; i++)
     {
         if (tracks[i].Path == filename)
         {
             tracks.RemoveAt(i);
             break;
         }
     }
 }
        public void RemovingFromFilteredCollectionDoesNotThrow()
        {
            var originalCollection = new ObservableCollection<ItemMetadata>();
            originalCollection.Add(new ItemMetadata("a"));
            originalCollection.Add(new ItemMetadata("b"));
            originalCollection.Add(new ItemMetadata("c"));
            IViewsCollection viewsCollection = new ViewsCollection(originalCollection, (i) => true);

            CollectionViewSource cvs = new CollectionViewSource {Source = viewsCollection};

            var view = cvs.View;
            try
            {
                originalCollection.RemoveAt(1);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
        }
Exemple #17
0
 //我要刺杀函数
 public void Kill()
 {
     CancelSelect();
     Step = 3;
     IsCenterHeroVisable = true;
     CenterHeros = new ObservableCollection<Hero>();
     CardRes.Heros.ForEach(x => CenterHeros.Add(x));
     CenterHeros.RemoveAt(0);
     CenterHeros.RemoveAt(0);
 }