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


C# ObservableCollection.Clear方法代码示例

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


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

示例1: TestCollectionSync

        public void TestCollectionSync()
        {
            string item0 = "Item0";
            string item1 = "Item1";
            string item2 = "Item2";
            string item3 = "Item3";

            ObservableCollection<string> collection = new ObservableCollection<string>();

            HelperLabeledViewModelCollection viewModel = new HelperLabeledViewModelCollection(null, collection, o => o);

            collection.Add(item0);
            collection.Add(item1);
            collection.Add(item3);
            Assert.IsTrue(CompareCollectionValues(collection, viewModel), "Add did not work.");

            collection.Insert(2, item2);
            Assert.IsTrue(CompareCollectionValues(collection, viewModel), "Insert did not work.");

            collection.Remove(item3);
            Assert.IsTrue(CompareCollectionValues(collection, viewModel), "Remove did not work.");

            collection.Move(0, 1);
            Assert.IsTrue(CompareCollectionValues(collection, viewModel), "Move did not work.");

            collection.Clear();
            Assert.IsTrue(CompareCollectionValues(collection, viewModel), "Clear did not work.");
        }
开发者ID:Zim-Code,项目名称:ViewModels,代码行数:28,代码来源:Test_LabeledViewModelCollection.cs

示例2: ColorGeneratorViewModel

        public ColorGeneratorViewModel()
        {
            m_colors = new ObservableCollection<RybColor>();

            m_generateColorsCommand = new RelayCommand(parameter =>
                {
                    string text = CountText;
                    if (text == null)
                        return;

                    int count;
                    if (int.TryParse(text, out count))
                    {
                        var colorsGenerator = new ColorGenerator(count);
                        m_colors.Clear();

                        for (int i = 0; i < count; i++)
                        {
                            var color = colorsGenerator.PickNextColor();
                            m_colors.Add(color);
                        }
                    }
                });

            CountText = "15";
        }
开发者ID:rpwjanzen,项目名称:RybColorGenerator,代码行数:26,代码来源:ColorGeneratorViewModel.cs

示例3: ClearTest

        public static void ClearTest()
        {
            string[] anArray = { "one", "two", "three", "four" };
            ObservableCollection<string> col = new ObservableCollection<string>(anArray);

            col.Clear();
            Assert.Equal(0, col.Count);
            Assert.Empty(col);

            Assert.Throws<ArgumentOutOfRangeException>(() => col[1]);

            //tests that the collectionChanged events are fired.
            CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
            col = new ObservableCollection<string>(anArray);
            helper.ClearTest(col);
        }
开发者ID:hitomi333,项目名称:corefx,代码行数:16,代码来源:ObservableCollection_MethodsTest.cs

示例4: ClearTest

        public static void ClearTest()
        {
            string[] anArray = { "one", "two", "three", "four" };
            ObservableCollection<string> col = new ObservableCollection<string>(anArray);

            col.Clear();
            Assert.Equal(0, col.Count);
            foreach (var item in col)
            {
                Assert.True(false, "Should not be able to iterate through an empty collection.");
            }

            Assert.Throws<ArgumentOutOfRangeException>(() => col[1]);
            
            //tests that the collectionChanged events are fired.
            CollectionAndPropertyChangedTester helper = new CollectionAndPropertyChangedTester();
            col = new ObservableCollection<string>(anArray);
            helper.ClearTest(col);
        }
开发者ID:johnhhm,项目名称:corefx,代码行数:19,代码来源:ObservableCollection_MethodsTest.cs

示例5: ConfigureAndTriggerSchedule

        private void ConfigureAndTriggerSchedule(DAL.Schedule currentSchedule)
        {
            Boolean CoreWorkingOK = true;

            si.sie("ConfigureAndTriggerSchedule");
            string allTickerText = "";
            KillTicker();

            Boolean tickerFound = false;
            TickerMetaToUse = "";
            contentCollection.Clear();

            try
            {
                //"text 0 690 1024 80 clWhite Arial 48 5"
                gridFive.Visibility = Visibility.Collapsed;
                gridFour.Visibility = Visibility.Collapsed;
                gridThree.Visibility = Visibility.Collapsed;
                gridTwo.Visibility = Visibility.Collapsed;

                #region CollectContentCollection
                try
                {
                    foreach (DAL.Content item in proxy.CollectMedia())
                    {
                        contentCollection.Add(item);
                    }
                }
                catch (Exception ex)
                {
                    CoreWorkingOK = false;
                    contentCollection.Clear();
                }

                si.sii("Content Collection Count = " + contentCollection.Count().ToString());


                //if there is an error the collection is cleared and loaded from xml, if it worked the collection is saved for future use
                if (contentCollection.Count > 0)
                {
                    SerializeContentCollection(@"c:\tmp\content.xml");
                }
                else
                {
                    contentCollection.Clear();
                    if (FTPONLY)
                    {
                        contentCollection = DeSerializeContentCollection(@"c:\tmp\xml\content.xml");
                    } 
                    else
                    {
                        contentCollection = DeSerializeContentCollection(@"c:\tmp\content.xml");
                    }
                };
                #endregion


                si.sii("Collecting Media in Content Collection");
                CollectMediaInContentCollection(); //Collect All Media
                si.sii("Collect this loop:"+currentSchedule.Loopname);

                #region CollectCurrentLoop
                try
                {
                    if (CoreWorkingOK)
                    {
                        currentLoop = proxy.CollectThisLoop(currentSchedule.Loopname); //Collect Loop
                        SerializeCurrentLoop(@"c:\tmp\loop.xml");
                    }
                    else
                    {
                        currentLoop = null;
                    }
                }
                catch (Exception)
                {
                    currentLoop = null;
                }

                if (currentLoop == null) si.sii("Current Loop is NULL possibly because Core isn't working - Collect from XML");
                si.sii("FTP Only Variable = "+FTPONLY.ToString());

                if (currentLoop == null)
                {
                    if (FTPONLY)
                    {
                        si.sii(@"INSIDE FTP ONLY - Deserializing c:\tmp\xml\loops.xml");
                        ObservableCollection<Loop> lc = new ObservableCollection<Loop>();
                        //DAL.LoopCollection lc = new LoopCollection();
                        try
                        {
                            lc = DeSerializeLoopCollection(@"c:\tmp\xml\loops.xml");
                            si.sii(@"Items in Loops.xml:"+lc.Count.ToString());
                        }
                        catch (Exception e3)
                        {
                            si.six(e3);
                        }
                        
                        foreach (var l in lc)
//.........这里部分代码省略.........
开发者ID:keyanmca,项目名称:_Signage,代码行数:101,代码来源:MainWindow.xaml.cs

示例6: CollectUpdatedScheduleForThisDisplay

        private void CollectUpdatedScheduleForThisDisplay()
        {
            si.sie("UpdateScheduleForThisDisplay");
            SimulateMouseClick();

            if (FTPONLY)
            {
                CollectXMLFileForFTPOnly();
            }

            try
            {
                //DAL.ScheduleCollection sch = new DAL.ScheduleCollection();
                ObservableCollection<Schedule> sch = new ObservableCollection<Schedule>();
                try
                {
                    sch = proxy.CollectScheduleForScreen();
                    SerializeScheduleCollection(@"c:\tmp\schedule.xml", sch);
                }
                catch (Exception)
                {
                    try
                    {
                        if (FTPONLY)
                        {
                            sch = DeSerializeScheduleCollection(@"c:\tmp\xml\schedule.xml");
                        } else
                        {
                            sch = DeSerializeScheduleCollection(@"c:\tmp\schedule.xml");    
                        }
                    }
                    catch (Exception)
                    {
                        sch.Clear();
                    }
                }
                
                si.sii("Current ClientID="+Properties.Settings.Default.ClientID);
                scheduleCollection.Clear();
                foreach (DAL.Schedule item in sch)
                {
                    if (Properties.Settings.Default.ClientID == item.Screenname || _GROUPID == item.Groupname)
                    {
                        scheduleCollection.Add(item);
                        si.sii(item.Loopname + ":" + item.Loopstart.ToString()+"/"+item.Screenname+"/"+item.Groupname);
                    }
                }

                try
                {
                    LastScheduleTick = proxy.CollectDelta("schedule");
                }
                catch (Exception)
                {
                }
                
            }
            catch (Exception ex)
            {
            }
            si.sil("UpdateScheduleForThisDisplay - "+scheduleCollection.Count().ToString()+" items in schedule");
        }
开发者ID:keyanmca,项目名称:_Signage,代码行数:62,代码来源:MainWindow.xaml.cs

示例7: ClearTest

        /// <summary>
        /// Clears the given Collection.
        /// </summary>
        public void ClearTest(ReadOnlyObservableCollection<string> readOnlyCol, ObservableCollection<string> collection)
        {
            INotifyPropertyChanged readOnlyPropertyChanged = readOnlyCol;
            readOnlyPropertyChanged.PropertyChanged += Collection_PropertyChanged;
            _expectedPropertyChanged = new[]
            {
                new PropertyNameExpected(COUNT),
                new PropertyNameExpected(ITEMARRAY)
            };

            INotifyCollectionChanged readOnlyCollectionChange = readOnlyCol;
            readOnlyCollectionChange.CollectionChanged += Collection_CollectionChanged;
            _expectedCollectionChangedFired++;
            _expectedAction = NotifyCollectionChangedAction.Reset;
            _expectedNewItems = null;
            _expectedNewStartingIndex = -1;
            _expectedOldItems = null;
            _expectedOldStartingIndex = -1;

            collection.Clear();
            Assert.Equal(0, 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 just cleared the collection.");

            readOnlyCollectionChange.CollectionChanged -= Collection_CollectionChanged;
            readOnlyPropertyChanged.PropertyChanged -= Collection_PropertyChanged;
        }
开发者ID:hitomi333,项目名称:corefx,代码行数:32,代码来源:ReadOnlyObservableCollection_EventsTests.cs

示例8: ListViewMouseLeftButtonDown

        /// <summary>
        /// Starts the Drag if the Item under the curser is a valid Drag Item
        /// </summary>
        /// <param name="sender">not used</param>
        /// <param name="e">MousePos</param>
        void ListViewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            int index = GetCurrentIndex(e.GetPosition);

            // check to see if drag can be done
            FrameworkElement ele = e.OriginalSource as FrameworkElement;
            if (ele != null && ele.DataContext != null)
            {
                if (ele.DataContext.GetType() != typeof(Mp3Song) && ele.DataContext.GetType() != typeof(Song))
                    return;
            }

            const DragDropEffects allowedEffects = DragDropEffects.Move;

            if (e.LeftButton != MouseButtonState.Pressed || e.ClickCount != 1)
                return;

            var draggSongs = new ObservableCollection<ISong>();

            foreach (ISong song in listView.SelectedItems)
                draggSongs.Add(song);

            ISong actDragSong = listView.Items[index] as ISong;

            if (listView.SelectedItems.Count < 2)
            {
                if (!draggSongs.Contains(actDragSong))
                    draggSongs.Clear();

                draggSongs.Add(actDragSong);
            }
            else
            {
                if (!draggSongs.Contains(actDragSong))
                    return;
            }

            try
            {
                DragDrop.DoDragDrop(listView, draggSongs, allowedEffects);
            }
            catch (ArgumentNullException)
            {}
            catch (NullReferenceException)
            {}

            ColorCurrentPlayedSong();
        }
开发者ID:mhack,项目名称:gamenoise,代码行数:53,代码来源:Standard.xaml.cs

示例9: FillDTUInfoOC

 public static void FillDTUInfoOC(ObservableCollection<DTUInfo> dtuInfoOc, string content, bool clear = true)
 {
     if (clear == true)
         dtuInfoOc.Clear();
     if (string.IsNullOrWhiteSpace(content))
         return;
     content = content.Trim(new char[] { '\0' });
     string[] sa = content.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
     if (sa == null || sa.Length < 1)
         return;
     foreach (string sai in sa)
     {
         string[] saia = sai.Split(new string[] { "\t" }, StringSplitOptions.None);
         if (saia == null || (saia.Length != Consts.DTU_INFO_ITEM_COUNT))
             continue;
         bool online = false;
         if (string.Compare(saia[4].Trim(), "y", true) == 0)
             online = true;
         DTUInfo dtui = new DTUInfo()
         {
             DtuId = saia[0].Trim(),
             SimId = saia[1].Trim(),
             UserName = saia[2].Trim(),
             UserTel = saia[3].Trim(),
             Online = online,
             DtLogString = saia[5].Trim(),
             Controller = (string.IsNullOrWhiteSpace(saia[6].Trim()) ?
             null :
             new UserInfo()
             {
                 UserName = saia[6].Trim()
             })
         };
         if (FindDTUInfo(saia[0].Trim(), dtuInfoOc) == null)
             dtuInfoOc.Add(dtui);
     }
 }
开发者ID:alpsxing,项目名称:Testempo,代码行数:37,代码来源:InformationTransferLibrary.cs

示例10: UpdateProducts

        private void UpdateProducts(ObservableCollection<Product> productList, IEnumerable<Product> productResults, bool completed)
        {
            if (productResults != null) {
                if (_clear) {
                    productList.Clear();
                    _clear = false;
                }

                foreach (Product p in productResults) {
                    productList.Add(p);
                }
            }

            Products = productList;

            if (ProductsLoaded != null) {
                ProductsLoaded(this, EventArgs.Empty);
            }

            if (completed) {
                _loading = false;
                RaisePropertyChanged("PriceRange", "IsLoading");
            }
        }
开发者ID:nikhilk,项目名称:silverlightfx,代码行数:24,代码来源:Catalog.cs

示例11: CopyGroupDescriptions

 /// <summary>
 /// Copies the <paramref name="from"/> collection to the <paramref name="to"/> collection
 /// </summary>
 /// <param name="from">The group descriptions to copy from</param>
 /// <param name="to">The group descriptions to copy to</param>
 private static void CopyGroupDescriptions(ObservableCollection<GroupDescription> from, ObservableCollection<GroupDescription> to)
 {
     to.Clear();
     foreach (GroupDescription gd in from)
     {
         to.Add(gd);
     }
 }
开发者ID:OpenRIAServices,项目名称:OpenRiaServices,代码行数:13,代码来源:DomainCollectionView.cs

示例12: AutoCompleteView

        /// <summary>
        /// Initializes a new instance of the <see cref="AutoCompleteView"/> class.
        /// </summary>
        public AutoCompleteView()
        {
            _availableSuggestions = new ObservableCollection<object>();
            _stkBase = new StackLayout();
            var innerLayout = new StackLayout();
            _entText = new Entry
            {
                HorizontalOptions = TextHorizontalOptions,
                VerticalOptions = TextVerticalOptions,
                TextColor = TextColor,
                BackgroundColor = TextBackgroundColor
            };
            _btnSearch = new Button
            {
                VerticalOptions = SearchVerticalOptions,
                HorizontalOptions = SearchHorizontalOptions,
                Text = SearchText
            };

            _lstSuggestions = new ListView
            {
                HeightRequest = SuggestionsHeightRequest,
                HasUnevenRows = true
            };

            innerLayout.Children.Add(_entText);
            innerLayout.Children.Add(_btnSearch);
            _stkBase.Children.Add(innerLayout);
            _stkBase.Children.Add(_lstSuggestions);

            Content = _stkBase;


            _entText.TextChanged += (s, e) =>
            {
                Text = e.NewTextValue;
                OnTextChanged(e);
            };
            _btnSearch.Clicked += (s, e) =>
            {
                if (SearchCommand != null && SearchCommand.CanExecute(Text))
                {
                    SearchCommand.Execute(Text);
                }
            };
            _lstSuggestions.ItemSelected += (s, e) =>
            {
                _entText.Text = e.SelectedItem.ToString();

                _availableSuggestions.Clear();
                ShowHideListbox(false);
                OnSelectedItemChanged(e.SelectedItem);

                if (ExecuteOnSuggestionClick
                   && SearchCommand != null
                   && SearchCommand.CanExecute(Text))
                {
                    SearchCommand.Execute(e);
                }
            };
            ShowHideListbox(false);
            _lstSuggestions.ItemsSource = _availableSuggestions;
        }
开发者ID:renatojunior2009,项目名称:Xamarin-Forms-Labs,代码行数:66,代码来源:AutoCompleteView.cs

示例13: Test_ObservableCollection_Clear

 public void Test_ObservableCollection_Clear()
 {
     var list = new ObservableCollection<int>() { 6, 5, 8 };
     Assert.Equal(3, list.Count);
     list.CollectionChanged += (o, e) =>
     {
         Assert.Same(list, o);
         Assert.Equal(NotifyCollectionChangedAction.Reset, e.Action);
         Assert.Null(e.NewItems);
         Assert.NotNull(e.OldItems);
         Assert.Equal(3, e.OldItems.Count);
         Assert.Equal(6, e.OldItems[0]);
         Assert.Equal(5, e.OldItems[1]);
         Assert.Equal(8, e.OldItems[2]);
     };
     list.Clear();
 }
开发者ID:fs7744,项目名称:ObjectValidator,代码行数:17,代码来源:ObservableCollection_Test.cs

示例14: ExplorerViewModel


//.........这里部分代码省略.........
                {
                    return;
                }

                ChangeStaredStatus(file);
            });

            AddFileCommand = new RelayCommand(UploadFile);

            EnableSelectionCommand = new RelayCommand(() =>
            {
                if (IsBusy)
                {
                    return;
                }

                IsSelectionEnabled = true;
            });

            RefreshFilesCommand = new RelayCommand(RefreshFiles);

            DeleteFilesCommand = new RelayCommand<IList>(files =>
            {
                _messageBoxService.Show("You are about to delete the selected files. Do you wish to proceed?", "Delete files?", new[] { "delete", "cancel" }, button =>
                {
                    if (button != 0)
                        return;

                    var filesArray = files
                        .Cast<GoogleFileViewModel>()
                        .ToArray();

                    IsSelectionEnabled = false;

                    DeleteFiles(filesArray);
                });
            });

            CreateNewFolderCommand = new RelayCommand(CreateNewFolder);

            RenameFileCommand = new RelayCommand<GoogleFileViewModel>(RenameFile);

            DeleteFileCommand = new RelayCommand<GoogleFileViewModel>(file =>
            {
                _messageBoxService.Show(string.Format("You are about to delete '{0}'. Do you wish to proceed?", file.Title), "Delete file?", new[] { "delete", "cancel" }, button =>
                {
                    if (button != 0)
                        return;

                    DeleteFile(file);
                });
            });

            ShowAboutCommand = new RelayCommand(() =>
            {
                _navigationService.NavigateTo("/View/AboutPage.xaml");
            });

            PageLoadedCommand = new RelayCommand(ExecuteInitialLoad);

            BackKeyPressCommand = new RelayCommand<CancelEventArgs>(e =>
            {
                GoogleDriveFile item;

                if (PivotSelectedIndex == 1)
                {
                    PivotSelectedIndex = 0;

                    e.Cancel = true;
                }
                else if (IsSelectionEnabled)
                {
                    IsSelectionEnabled = false;

                    e.Cancel = true;
                }
                else if (_mainModel.TryPop(out item))
                {
                    AbortCurrentCall();

                    RaisePropertyChanged(() => CurrentPath);

                    RefreshFiles();

                    e.Cancel = true;
                }
                else
                {
                    AbortCurrentCall(true);

                    Files.Clear();
                    PictureFiles.Clear();
                }
            });

            MessengerInstance.Register<RefreshFilesMessage>(this, message =>
            {
                DispatcherHelper.RunAsync(RefreshFiles);
            });
        }
开发者ID:Hitchhikrr,项目名称:GDrive,代码行数:101,代码来源:ExplorerViewModel.cs

示例15: ChangingContentsOfObservableCollectionUpdatesTreeMap

 public void ChangingContentsOfObservableCollectionUpdatesTreeMap()
 {
     TreeMap treeMap = new TreeMap();
     ObservableCollection<int> itemsSource = new ObservableCollection<int>();
     treeMap.ItemsSource = itemsSource;
     TestAsync(
         treeMap,
         // +1 because of the Border in default template
         () => Assert.AreEqual(0 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => itemsSource.Add(1),
         () => Assert.AreEqual(1 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => itemsSource.Add(1),
         () => Assert.AreEqual(2 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()),
         () => itemsSource.Clear(),
         () => Assert.AreEqual(0 + 1, treeMap.GetVisualDescendents().OfType<Border>().Count()));
 }
开发者ID:shijiaxing,项目名称:SilverlightToolkit,代码行数:16,代码来源:TreeMapTest.cs


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