当前位置: 首页>>代码示例>>C#>>正文


C# ObservableCollection.RemoveAt方法代码示例

本文整理汇总了C#中System.Collections.ObservableCollection.RemoveAt方法的典型用法代码示例。如果您正苦于以下问题:C# ObservableCollection.RemoveAt方法的具体用法?C# ObservableCollection.RemoveAt怎么用?C# ObservableCollection.RemoveAt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Collections.ObservableCollection的用法示例。


在下文中一共展示了ObservableCollection.RemoveAt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Test_ObservableCollection_Remove

        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);
        }
开发者ID:fs7744,项目名称:ObjectValidator,代码行数:27,代码来源:ObservableCollection_Test.cs

示例2: Main

    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);
    }
开发者ID:Rostech,项目名称:AdvancedDataStructures,代码行数:11,代码来源:ObservableCollectionDemo.cs

示例3: RemoveItemAtTest

        /// <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;
        }
开发者ID:hitomi333,项目名称:corefx,代码行数:38,代码来源:ReadOnlyObservableCollection_EventsTests.cs

示例4: RemoveAtTest_Negative

        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);
            }
        }
开发者ID:hitomi333,项目名称:corefx,代码行数:21,代码来源:ReadOnlyObservableCollection_EventsTests.cs

示例5: RemoveAtTest_Negative

        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);
            }
        }
开发者ID:johnhhm,项目名称:corefx,代码行数:23,代码来源:ObservableCollection_MethodsTest.cs

示例6: RemoveAtTest

        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);
        }
开发者ID:johnhhm,项目名称:corefx,代码行数:30,代码来源:ObservableCollection_MethodsTest.cs

示例7: OnRemoveNotifyCollectionChangedThenIndexProvided

        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);
                });
        }
开发者ID:xperiandri,项目名称:PortablePrism,代码行数:18,代码来源:ViewsCollectionFixture.cs

示例8: RemoveTracks

 /// <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;
         //}
     }
 }
开发者ID:Erls-Corporation,项目名称:YAMA,代码行数:38,代码来源:MainWindow.xaml.cs

示例9: CheckObjectValidationForFields

        /// <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));
                }
            }
        }
开发者ID:JaysonJG,项目名称:Catel,代码行数:35,代码来源:WarningAndErrorValidator.cs

示例10: UpdateUnconsumedProperties

 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);
         }
     }
 }
开发者ID:iskiselev,项目名称:JSIL.NetFramework,代码行数:10,代码来源:CategoryContainer.xaml.cs

示例11: SetItemsSourceAndModifyCollection

        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();
        }
开发者ID:kvervo,项目名称:HorizontalLoopingSelector,代码行数:71,代码来源:ItemsSource.cs

示例12: SynchronizeGroupDescriptions

        // 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)); 
            }
        } 
开发者ID:sjyanxin,项目名称:WPFSource,代码行数:93,代码来源:ItemCollection.cs

示例13: ObservableCollectionTest

        //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);
            }
        }
开发者ID:vjzr-Phonex,项目名称:C_Sharp,代码行数:17,代码来源:Program.cs

示例14: OnRemoveOfFilterMatchingItemThenViewCollectionRelativeIndexProvided

        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);
        }
开发者ID:selvendiranj,项目名称:compositewpf-copy,代码行数:15,代码来源:ViewsCollectionFixture.cs

示例15: RemoveTrack

 /// <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;
         }
     }
 }
开发者ID:Erls-Corporation,项目名称:YAMA,代码行数:16,代码来源:MainWindow.xaml.cs


注:本文中的System.Collections.ObservableCollection.RemoveAt方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。