Esempio n. 1
0
 /// <summary>
 /// Låter andra klasser lyssna på förändringar i repositoryt så att de kan uppdateras.
 /// </summary>
 /// <param name="handler"></param>
 /// <returns>Referns till en instans av FDRFeedRepository med eventhanterare</returns>
 public static IRepository<Feed> getFeeds(NotifyCollectionChangedEventHandler handler)
 {
     if (feeds == null)
         feeds = new FDRFeedRepository();
     feeds.CollectionChanged += handler;
     return feeds;
 }
Esempio n. 2
0
 public void AddHandler(NotifyCollectionChangedEventHandler handler)
 {
     if(handler != null)
     {
         _books.CollectionChanged += handler;
     }
 }
 public ItemsSourceCollectionViewSource([NotNull] UICollectionView collectionView,
     string itemTemplate = AttachedMemberConstants.ItemTemplate)
     : base(collectionView, itemTemplate)
 {
     _weakHandler = ReflectionExtensions.MakeWeakCollectionChangedHandler(this,
         (adapter, o, arg3) => adapter.OnCollectionChanged(o, arg3));
 }
    public GeneratorNodeFactory( NotifyCollectionChangedEventHandler itemsChangedHandler,
                                 NotifyCollectionChangedEventHandler groupsChangedHandler,
                                 EventHandler<ExpansionStateChangedEventArgs> expansionStateChangedHandler,
                                 EventHandler isExpandedChangingHandler,
                                 EventHandler isExpandedChangedHandler,
                                 DataGridControl dataGridControl )
    {
      if( itemsChangedHandler == null )
        throw new ArgumentNullException( "itemsChangedHandler" );

      if( groupsChangedHandler == null )
        throw new ArgumentNullException( "groupsChangedHandler" );

      if( expansionStateChangedHandler == null )
        throw new ArgumentNullException( "expansionStateChangedHandler" );

      if( isExpandedChangingHandler == null )
        throw new ArgumentNullException( "isExpandedChangingHandler" );

      if( isExpandedChangedHandler == null )
        throw new ArgumentNullException( "isExpandedChangedHandler" );

      m_itemsChangedHandler = itemsChangedHandler;
      m_groupsChangedHandler = groupsChangedHandler;
      m_expansionStateChangedHandler = expansionStateChangedHandler;
      m_isExpandedChangingHandler = isExpandedChangingHandler;
      m_isExpandedChangedHandler = isExpandedChangedHandler;

      if( dataGridControl != null )
      {
        m_dataGridControl = new WeakReference( dataGridControl );
      }
    }
 public CollectionChangedEventListener(INotifyCollectionChanged source, NotifyCollectionChangedEventHandler handler)
 {
     if (source == null) { throw new ArgumentNullException("source"); }
     if (handler == null) { throw new ArgumentNullException("handler"); }
     this.source = source;
     this.handler = handler;
 }
Esempio n. 6
0
 /// <summary>
 /// Låter andra klasser lyssna på förändringar i repositoryt så att de kan uppdateras.
 /// </summary>
 /// <param name="handler"></param>
 /// <returns>Referns till en instans av FDRCategoryRepository med eventhanterare</returns>
 public static IRepository<Category> getCategories(NotifyCollectionChangedEventHandler handler)
 {
     if (categories == null)
         categories = new FDRCategoryRepository();
     categories.CollectionChanged += handler;
     return categories;
 }
Esempio n. 7
0
        public static void OnAutoScrollToEndChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
        {
            var ctrl = s as ItemsControl;
            if (ctrl == null)
                throw new InvalidOperationException("This attached property only supports ItemsControl or derived types.");

            var data = ctrl.Items as INotifyCollectionChanged;
            if (data == null)
                throw new InvalidOperationException("Collection does not support change notifications.");

            Control parentCtrl = ctrl;
            while (parentCtrl != null && parentCtrl.GetType() != typeof(ScrollViewer))
                parentCtrl = parentCtrl.Parent as Control;
            ScrollViewer sv = parentCtrl as ScrollViewer;

            var scrollToEndHandler = new NotifyCollectionChangedEventHandler(
                (s1, e1) =>
                {
                    if (e1.Action == NotifyCollectionChangedAction.Add && sv != null)
                        sv.ScrollToBottom();
                });

            if ((bool)e.NewValue)
                data.CollectionChanged += scrollToEndHandler;
            else
                data.CollectionChanged -= scrollToEndHandler;
        }
Esempio n. 8
0
        public static void OnAutoScrollChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
        {
            var val = (bool)e.NewValue;
            var lb = s as ListView;
            if (lb == null)
                throw new InvalidOperationException("This behavior can only be attached to a ListView.");

            var ic = lb.Items;
            var data = ic.SourceCollection as INotifyCollectionChanged;
            if (data == null) return;

            var autoscroller = new NotifyCollectionChangedEventHandler(
                (s1, e1) =>
                {
                    var selectedItem = default(object);
                    switch (e1.Action)
                    {
                        case NotifyCollectionChangedAction.Add:
                        case NotifyCollectionChangedAction.Move: selectedItem = e1.NewItems[e1.NewItems.Count - 1]; break;
                        case NotifyCollectionChangedAction.Remove: if (ic.Count < e1.OldStartingIndex) { selectedItem = ic[e1.OldStartingIndex - 1]; } else if (ic.Count > 0) selectedItem = ic[0]; break;
                        case NotifyCollectionChangedAction.Reset: if (ic.Count > 0) selectedItem = ic[0]; break;
                    }

                    if (selectedItem == default(object)) return;
                    ic.MoveCurrentTo(selectedItem);
                    lb.ScrollIntoView(selectedItem);
                });

            if (val) data.CollectionChanged += autoscroller;
            else data.CollectionChanged -= autoscroller;
        }
        public static void OnAutoScrollToEndChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
        {
            var listBox = s as ListBox;
            if(listBox==null)
                return;
            var listBoxItems = listBox.Items;
            var data = listBoxItems.SourceCollection as INotifyCollectionChanged;
            if (data == null)
                return;

            var scrollToEndHandler = new NotifyCollectionChangedEventHandler(
                (s1, e1) =>
                {
                    if (listBox.Items.Count <= 0) 
                        return;
                    var lastItem = listBox.Items[listBox.Items.Count - 1];
                    listBoxItems.MoveCurrentTo(lastItem);
                    listBox.ScrollIntoView(lastItem);
                });

            if ((bool)e.NewValue)
                data.CollectionChanged += scrollToEndHandler;
            else
                data.CollectionChanged -= scrollToEndHandler;
        }
 public MvvmPickerViewModel([NotNull] UIPickerView pickerView)
 {
     Should.NotBeNull(pickerView, "pickerView");
     _pickerView = ServiceProvider.WeakReferenceFactory(pickerView);
     _weakHandler = ReflectionExtensions.MakeWeakCollectionChangedHandler(this,
         (adapter, o, arg3) => adapter.OnCollectionChanged(o, arg3));
     EmptyTitle = "-";
 }
Esempio n. 11
0
        /// <summary>
        /// Hookups the handler to the collection changed event. When the value changes it removes the handler.
        /// </summary>
        /// <param name="oldValue">The old collection.</param>
        /// <param name="newValue">The new collection.</param>
        /// <param name="handler">The handler to hookup.</param>
        public static void HookupToCollectionChanged(INotifyCollectionChanged oldValue, INotifyCollectionChanged newValue,
            NotifyCollectionChangedEventHandler handler)
        {
            if (oldValue != null)
                oldValue.CollectionChanged -= handler;

            if (newValue != null)
                newValue.CollectionChanged += handler;
        }
Esempio n. 12
0
		public EventTracker(IVisualElementRenderer renderer)
		{
			if (renderer == null)
				throw new ArgumentNullException("renderer");

			_collectionChangedHandler = ModelGestureRecognizersOnCollectionChanged;

			_renderer = renderer;
			_renderer.ElementChanged += OnElementChanged;
		}
    public PropertiesWindowViewModel(PropertiesWindow propertiesWindow)
    {
      this.propertiesWindow = propertiesWindow;
      onSelectionChanged = (sender, args) =>
      {
        SelectionChanged(sender, args);
      };

      Items = new ObservableCollection<PropertySingleItem>();
    }
Esempio n. 14
0
		private static void Subscribe(DataGrid dataGrid)
		{
			var handler = new NotifyCollectionChangedEventHandler((sender, eventArgs) => ScrollToEnd(dataGrid));
			if (handlersDict.ContainsKey(dataGrid))
			{
				return;
			}
            handlersDict.Add(dataGrid, handler);
			((INotifyCollectionChanged)dataGrid.Items).CollectionChanged += handler;
			ScrollToEnd(dataGrid);
		}
Esempio n. 15
0
        /// <summary>
        /// Adds a weak event listener for a CollectionChanged event.
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="handler">The event handler.</param>
        /// <exception cref="ArgumentNullException">source must not be <c>null</c>.</exception>
        /// <exception cref="ArgumentNullException">handler must not be <c>null</c>.</exception>
        protected void AddWeakEventListener(INotifyCollectionChanged source, NotifyCollectionChangedEventHandler handler)
        {
            if (source == null) { throw new ArgumentNullException("source"); }
            if (handler == null) { throw new ArgumentNullException("handler"); }

            CollectionChangedEventListener listener = new CollectionChangedEventListener(source, handler);

            collectionChangedListeners.Add(listener);

            CollectionChangedEventManager.AddListener(source, listener);
        }
 private static void SetupOnUnloadedHandler(DependencyObject dependencyObject, INotifyCollectionChanged observableCollection,
                                            NotifyCollectionChangedEventHandler sourceChangedHandler)
 {
     RoutedEventHandler unloadedEventHandler = null;
     unloadedEventHandler = (sender, args) =>
                                {
                                    observableCollection.CollectionChanged -= sourceChangedHandler;
                                    ((ListViewBase)sender).SelectionChanged -= OnGridSelectionChanged;
                                    ((ListViewBase)sender).Unloaded -= unloadedEventHandler;
                                };
     ((ListViewBase)dependencyObject).Unloaded += unloadedEventHandler;
 }
        public override void Dispose()
        {
            if (IsDisposed) return;

            foreach (var kvp in myObservedCollections)
                kvp.Value ();
            myObservedCollections.Clear();
            myObservedCollections = null;

            myCollectionChangedEventHandler = null;

            base.Dispose ();
        }
Esempio n. 18
0
        protected void RemoveEventListener(INotifyCollectionChanged source, NotifyCollectionChangedEventHandler handler)
        {
            if (source == null) { throw new ArgumentException("source"); }
            if (handler == null) { throw new ArgumentException("handler"); }

            CollectionChangedEventListener listener = collectionEventListeners.LastOrDefault(c => c.Source == source && c.Handler == handler);

            if (listener != null)
            {
                collectionEventListeners.Remove(listener);
                CollectionChangedEventManager.RemoveListener(source, listener);
            }
        }
Esempio n. 19
0
        public DataMappingViewModel(IWebActivity activity, NotifyCollectionChangedEventHandler mappingCollectionChangedEventHandler = null)
        {
            _activity = activity;
            _actionManager = new ActionManager();
            Inputs = new ObservableCollection<IInputOutputViewModel>();
            Outputs = new ObservableCollection<IInputOutputViewModel>();

            if(mappingCollectionChangedEventHandler != null)
            {
                Inputs.CollectionChanged += mappingCollectionChangedEventHandler;
                Outputs.CollectionChanged += mappingCollectionChangedEventHandler;
            }
            Initialize(_activity);
        }
 public ItemsSourcePagerAdapter([NotNull] ViewPager viewPager)
 {
     Should.NotBeNull(viewPager, nameof(viewPager));
     _viewPager = viewPager;
     _fragmentManager = viewPager.GetFragmentManager();
     _itemTemplateProvider = new DataTemplateProvider(viewPager, AttachedMemberConstants.ItemTemplate, AttachedMemberConstants.ItemTemplateSelector);
     _weakHandler = ReflectionExtensions.MakeWeakCollectionChangedHandler(this, (adapter, o, arg3) => adapter.OnCollectionChanged(o, arg3));
     var activityView = _viewPager.Context.GetActivity() as IActivityView;
     if (activityView != null)
     {
         _listener = ReflectionExtensions.CreateWeakEventHandler<ItemsSourcePagerAdapter, EventArgs>(this, (adapter, o, arg3) => adapter.ActivityViewOnDestroyed((Activity)o));
         activityView.Mediator.Destroyed += _listener.Handle;
     }
 }
Esempio n. 21
0
        private static void Subscribe(DataGrid dataGrid)
        {
            if (infoDict.ContainsKey(dataGrid))
                return;

            var timer = new DispatcherTimer(DispatcherPriority.Background);
            var handler = new NotifyCollectionChangedEventHandler((sender, eventArgs) => timer.Start());

            infoDict.Add(dataGrid, new DataGridInfo(handler, timer));

            timer.Tick += (sender, args) => ScrollToEnd(dataGrid);
            ((INotifyCollectionChanged)dataGrid.Items).CollectionChanged += handler;
            
            timer.Start();
        }
 internal void HandleToolCollectionNotification(NotifyCollectionChangedEventHandler listener, bool register)
 {
     if (null == listener)
     {
         throw FxTrace.Exception.ArgumentNull("listener");
     }
     if (register)
     {
         this.tools.CollectionChanged += listener;
     }
     else
     {
         this.tools.CollectionChanged -= listener;
     }
 }
 /// <summary>
 ///     Initializes a new instance of the <see cref="ItemsSourceAdapter" /> class.
 /// </summary>
 public ItemsSourceRecyclerAdapter([NotNull] global::Android.Support.V7.Widget.RecyclerView recyclerView)
 {
     Should.NotBeNull(recyclerView, "recyclerView");
     _recyclerView = recyclerView;
     _itemTemplateProvider = new DataTemplateProvider(_recyclerView, AttachedMemberConstants.ItemTemplate,
         AttachedMemberConstants.ItemTemplateSelector);
     _layoutInflater = _recyclerView.Context.GetBindableLayoutInflater();
     _weakHandler = ReflectionExtensions.MakeWeakCollectionChangedHandler(this,
         (adapter, o, arg3) => adapter.OnCollectionChanged(o, arg3));
     var activityView = _recyclerView.Context.GetActivity() as IActivityView;
     if (activityView != null)
     {
         _listener = ReflectionExtensions.CreateWeakEventHandler<ItemsSourceRecyclerAdapter, EventArgs>(this, (adapter, o, arg3) => adapter.ActivityViewOnDestroyed((Activity)o));
         activityView.Mediator.Destroyed += _listener.Handle;
     }
 }
Esempio n. 24
0
        /// <summary>
        /// This method will be called when the AutoScrollToEnd
        /// property was changed
        /// </summary>
        /// <param name="s">The sender (the ListBox)</param>
        /// <param name="e">Some additional information</param>
        public static void OnAutoScrollToEndChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
        {
            var listView = s as ListView;
            if (listView != null)
            {
                var listViewItems = listView.Items;
                var data = listViewItems.SourceCollection as INotifyCollectionChanged;

                var scrollToEndHandler = new NotifyCollectionChangedEventHandler(
                    (s1, e1) =>
                        {
                            if (listView.Items.Count > 0 && e1 != null && e1.NewItems != null) // fix for error in certain conditions
                            {
                                //object lastItem = listView.Items[listView.Items.Count - 1];
                                var lastItem = e1.NewItems[0];
                                listView.Items.MoveCurrentTo(lastItem);
                                listView.ScrollIntoView(lastItem);
                                listView.SelectedItem = lastItem;
                            }
                        });

                var gotFocusHandler = new RoutedEventHandler (
                    (s2, e2) =>
                    {
                        if (listView.Items.Count > 0)
                        {
                            //object lastItem = listView.Items[listView.Items.Count - 1];
                            listView.ScrollIntoView(listView.SelectedItem);
                        }
                    });

                if ((bool)e.NewValue)
                {
                    if (data != null)
                    {
                        data.CollectionChanged += scrollToEndHandler;
                        listView.GotFocus += gotFocusHandler;
                    }
                }
                else if (data != null)
                {
                    data.CollectionChanged -= scrollToEndHandler;
                    listView.GotFocus -= gotFocusHandler;
                }
            }
        }
        public void Advertisements_WhenNewItemAdded_CallsCollectionChangedEvent()
        {
            //	Arrange
            var paperVm = GetValidNewspaperItemViewModel();
            var adVm = GetValidAdvertisementItemViewModel();
            IList addedItems = new ArrayList();

            var collectionChangedEvent = new NotifyCollectionChangedEventHandler((sender, arg) => { addedItems = arg.NewItems; });
            paperVm.Advertisements.CollectionChanged += collectionChangedEvent;

            //	Act
            paperVm.Advertisements.Add(adVm);

            //	Assert
            addedItems.Count.Should().Be(1, "One item was added");
            adVm.Should().Be(addedItems[0]);
        }
Esempio n. 26
0
        public static void OnIsAutoScrollChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            var value = (bool)e.NewValue;
            var listView = obj as ListView;
            var itemCollection = listView.Items;
            var data = (INotifyCollectionChanged)itemCollection;

            var autoscroller = new NotifyCollectionChangedEventHandler(
                (o, arg) =>
                {
                    var selectedItem = default(object);
                    switch (arg.Action)
                    {
                        case NotifyCollectionChangedAction.Add:
                        case NotifyCollectionChangedAction.Move:
                            {
                                selectedItem = arg.NewItems[arg.NewItems.Count - 1];
                                break;
                            }
                        case NotifyCollectionChangedAction.Remove:
                            {
                                if (itemCollection.Count < arg.OldStartingIndex)
                                {
                                    selectedItem = itemCollection[arg.OldStartingIndex - 1];
                                }
                                else if (itemCollection.Count > 0) selectedItem = itemCollection[0];
                                break;
                            }
                        case NotifyCollectionChangedAction.Reset:
                            {
                                if (itemCollection.Count > 0) selectedItem = itemCollection[0];
                                break;
                            }
                    }
                    if (selectedItem != default(object))
                    {
                        itemCollection.MoveCurrentTo(selectedItem);
                        listView.ScrollIntoView(selectedItem);
                    }
                });
            if (value) data.CollectionChanged += autoscroller;
            else data.CollectionChanged -= autoscroller;
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        private static void AssertChange(
            ObservableCollection<int> original,
            Action<ObservableCollection<int>> change,
            ICollection copy,
            NotifyCollectionChangedEventHandler handler)
        {
            try
            {
                change(original);
                CollectionAssert.AreEqual(original, copy);
            }
            finally
            {
                original.CollectionChanged -= handler;
            }

            original.Add(42);
            CollectionAssert.AreNotEqual(original, copy);
        }
Esempio n. 28
0
        public static void InvokeCollectionChanged(NotifyCollectionChangedEventHandler collectionChanged, object sender, NotifyCollectionChangedEventArgs e)
        {
            foreach (NotifyCollectionChangedEventHandler nh in collectionChanged.GetInvocationList())
            {
                var dispObj = nh.Target as DispatcherObject;
                if (dispObj != null)
                {
                    Dispatcher dispatcher = dispObj.Dispatcher;
                    if (dispatcher != null && !dispatcher.CheckAccess())
                    {
                        NotifyCollectionChangedEventHandler nh1 = nh;
                        dispatcher.BeginInvoke((Action) (() => nh1.Invoke(sender, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset))),
                            DispatcherPriority.DataBind);
                        continue;
                    }
                }

                nh.Invoke(sender, IsRangeAction(e) ? new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset) : e);
            }
        }
 /// <summary>
 ///     Initializes a new instance of the <see cref="ItemsSourceAdapter" /> class.
 /// </summary>
 public ItemsSourceAdapter([NotNull] object container, Context context, bool listenCollectionChanges, string dropDownItemTemplateSelectorName = null,
     string itemTemplateSelectorName = AttachedMemberConstants.ItemTemplateSelector, string dropDownItemTemplateIdName = null,
     string itemTemplateIdName = AttachedMemberConstants.ItemTemplate)
 {
     Should.NotBeNull(container, "container");
     _container = container;
     _itemTemplateProvider = new DataTemplateProvider(container, itemTemplateIdName, itemTemplateSelectorName);
     _dropDownTemplateProvider = new DataTemplateProvider(container,
         dropDownItemTemplateIdName ?? AttachedMembers.AdapterView.DropDownItemTemplate,
         dropDownItemTemplateSelectorName ?? AttachedMembers.AdapterView.DropDownItemTemplateSelector);
     _layoutInflater = context.GetBindableLayoutInflater();
     if (listenCollectionChanges)
         _weakHandler = ReflectionExtensions.MakeWeakCollectionChangedHandler(this, (adapter, o, arg3) => adapter.OnCollectionChanged(o, arg3));
     var activityView = context.GetActivity() as IActivityView;
     if (activityView != null)
     {
         _listener = ReflectionExtensions.CreateWeakEventHandler<ItemsSourceAdapter, EventArgs>(this, (adapter, o, arg3) => adapter.ActivityViewOnDestroyed((Activity)o));
         activityView.Mediator.Destroyed += _listener.Handle;
     }
 }
        protected override void StartListening(object source)
        {
            //Check if we can subscribe to the source
            INotifyCollectionChanged INotify = source as INotifyCollectionChanged;
            System.Diagnostics.Debug.Assert(INotify != null, "Attempt to create weak subscription to object that does not support it");
            if (INotify == null)
                return;

            NotifyCollectionChangedEventHandler eventHandler = new NotifyCollectionChangedEventHandler(this.OnEvent);
            eventHandler = ObjectToHandler.GetOrAdd(source, eventHandler);

            INotify.CollectionChanged += eventHandler;

            if (CleanupCountdown == 0)
            {
                this.ScheduleCleanup();
                CleanupCountdown = 5000;
            }

            CleanupCountdown--;
        }
Esempio n. 31
0
 public PropertyNotifier(INotifyCollectionChanged obj, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, IList changedItems)
 {
     this.collectionChangedObject    = obj;
     this.collectionChangedHandler   = collectionChangedHandler;
     this.collectionChangedEventArgs = new NotifyCollectionChangedEventArgs(action, changedItems);
 }
Esempio n. 32
0
        public void CollectionChanged_WhenUnsubscribed_ShouldStopReceivingNotifications()
        {
            _realm.Write(() =>
            {
                _realm.Add(new OrderedObject
                {
                    Order           = 0,
                    IsPartOfResults = true
                });
            });

            Exception error = null;

            _realm.Error += (sender, e) =>
            {
                error = e.GetException();
            };

            var query  = _realm.All <OrderedObject>().Where(o => o.IsPartOfResults).OrderBy(o => o.Order).AsRealmCollection();
            var handle = GCHandle.Alloc(query); // prevent this from being collected across event loops

            try
            {
                // wait for the initial notification to come through
                TestHelpers.RunEventLoop();

                var eventArgs = new List <NotifyCollectionChangedEventArgs>();
                var handler   = new NotifyCollectionChangedEventHandler((sender, e) =>
                {
                    eventArgs.Add(e);
                });
                query.CollectionChanged += handler;

                Assert.That(error, Is.Null);

                _realm.Write(() =>
                {
                    _realm.Add(new OrderedObject
                    {
                        Order           = 1,
                        IsPartOfResults = true
                    });
                });

                TestHelpers.RunEventLoop();

                Assert.That(error, Is.Null);
                Assert.That(eventArgs.Count, Is.EqualTo(1));
                Assert.That(eventArgs[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Add));

                _realm.Write(() =>
                {
                    _realm.Add(new OrderedObject
                    {
                        Order           = 2,
                        IsPartOfResults = true
                    });
                });

                TestHelpers.RunEventLoop();

                Assert.That(error, Is.Null);
                Assert.That(eventArgs.Count, Is.EqualTo(2));
                Assert.That(eventArgs.All(e => e.Action == NotifyCollectionChangedAction.Add));

                query.CollectionChanged -= handler;

                _realm.Write(() =>
                {
                    _realm.Add(new OrderedObject
                    {
                        Order           = 3,
                        IsPartOfResults = true
                    });
                });

                TestHelpers.RunEventLoop();

                Assert.That(error, Is.Null);
                Assert.That(eventArgs.Count, Is.EqualTo(2));
                Assert.That(eventArgs.All(e => e.Action == NotifyCollectionChangedAction.Add));
            }
            finally
            {
                handle.Free();
            }
        }
Esempio n. 33
0
 public static PropertyNotifier Notify(this INotifyCollectionChanged obj, PropertyChangingEventHandler propertyChangingHandler, PropertyChangedEventHandler propertyChangedHandler, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, object newItem, object oldItem, int index, params string[] properties)
 {
     return(new PropertyNotifier(obj, propertyChangingHandler, propertyChangedHandler, collectionChangedHandler, action, newItem, oldItem, index, properties));
 }
 /// <summary>
 /// Clears all <see cref="CollectionChanged"/> event handlers
 /// </summary>
 public void ClearCollectionChangedEvents() => _changed = null;
Esempio n. 35
0
 public WeakHandler(object source, NotifyCollectionChangedEventHandler originalHandler)
 {
     this.source          = new WeakReference(source);
     this.originalHandler = new WeakReference(originalHandler);
 }
        private static IObservable <CollectionChangedData <TItem> > ItemsPropertyChange <TCollection, TItem>(
            TCollection collection,
            Predicate <string> isPropertyNameRelevant)
            where TCollection : IList <TItem>, INotifyCollectionChanged
        {
            return(Observable.Create <CollectionChangedData <TItem> >(
                       o =>
            {
                var trackedItems = new List <INotifyPropertyChanged>();
                PropertyChangedEventHandler onItemChanged =
                    (sender, e) =>
                {
                    if (isPropertyNameRelevant(e.PropertyName))
                    {
                        var payload = new CollectionChangedData <TItem>((TItem)sender);
                        o.OnNext(payload);
                    }
                };
                Action <IEnumerable <TItem> > registerItemChangeHandlers =
                    items =>
                {
                    foreach (var notifier in items.OfType <INotifyPropertyChanged>())
                    {
                        trackedItems.Add(notifier);
                        notifier.PropertyChanged += onItemChanged;
                    }
                };
                Action <IEnumerable <TItem> > unRegisterItemChangeHandlers =
                    items =>
                {
                    foreach (var notifier in items.OfType <INotifyPropertyChanged>())
                    {
                        notifier.PropertyChanged -= onItemChanged;
                        trackedItems.Remove(notifier);
                    }
                };
                NotifyCollectionChangedEventHandler onCollectionChanged =
                    (sender, e) =>
                {
                    if (e.Action == NotifyCollectionChangedAction.Reset)
                    {
                        foreach (var notifier in trackedItems)
                        {
                            notifier.PropertyChanged -= onItemChanged;
                        }

                        var payload = new CollectionChangedData <TItem>(trackedItems, collection);
                        trackedItems.Clear();
                        registerItemChangeHandlers(collection);
                        o.OnNext(payload);
                    }
                    else
                    {
                        var payload = new CollectionChangedData <TItem>(e);
                        unRegisterItemChangeHandlers(payload.OldItems);
                        registerItemChangeHandlers(payload.NewItems);
                        o.OnNext(payload);
                    }
                };

                registerItemChangeHandlers(collection);
                collection.CollectionChanged += onCollectionChanged;

                return Disposable.Create(
                    () =>
                {
                    collection.CollectionChanged -= onCollectionChanged;
                    unRegisterItemChangeHandlers(collection);
                });
            }));
        }
 public PropertyNotifier(INotifyCollectionChanged obj, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, object newItem, object oldItem, int index)
 {
     this.collectionChangedObject    = obj;
     this.collectionChangedHandler   = collectionChangedHandler;
     this.collectionChangedEventArgs = new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index);
 }
 public static PropertyNotifier Notify(this INotifyCollectionChanged obj, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, object newItem, object oldItem, int index)
 {
     return(new PropertyNotifier(obj, collectionChangedHandler, action, newItem, oldItem, index));
 }
 public static PropertyNotifier Notify(this INotifyCollectionChanged obj, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, IList newItems, IList oldItems)
 {
     return(new PropertyNotifier(obj, collectionChangedHandler, action, newItems, oldItems));
 }
Esempio n. 40
0
        private void initializeFromSource()
        {
            if (_sourceNotifyCollectionChangedEventHandler != null)
            {
                int itemInfosCount = _itemInfos.Count;
                for (int index = 0; index < itemInfosCount; index++)
                {
                    ItemInfo          itemInfo          = _itemInfos[index];
                    ExpressionWatcher expressionWatcher = itemInfo.ExpressionWatcher;
                    expressionWatcher.Dispose();
                }

                int capacity = _sourceScalar != null?Utils.getCapacity(_sourceScalar) : Utils.getCapacity(_source);

                _itemInfos       = new List <ItemInfo>(capacity);
                _sourcePositions = new Positions <ItemInfo>(_itemInfos);

                if (_rootSourceWrapper)
                {
                    _sourceAsList.CollectionChanged -= _sourceNotifyCollectionChangedEventHandler;
                }
                else
                {
                    _sourceAsList.CollectionChanged -= _sourceWeakNotifyCollectionChangedEventHandler.Handle;
                    _sourceWeakNotifyCollectionChangedEventHandler = null;
                }

                _sourceNotifyCollectionChangedEventHandler = null;
            }

            _predicatePassedCount = 0;
            if (_sourceScalar != null)
            {
                _source = _sourceScalar.Value;
            }
            _sourceAsList = null;

            if (_source != null)
            {
                if (_source is ObservableCollectionWithChangeMarker <TSourceItem> sourceAsList)
                {
                    _sourceAsList      = sourceAsList;
                    _rootSourceWrapper = false;
                }
                else
                {
                    _sourceAsList      = new RootSourceWrapper <TSourceItem>(_source);
                    _rootSourceWrapper = true;
                }

                _lastProcessedSourceChangeMarker = _sourceAsList.ChangeMarkerField;

                int count = _sourceAsList.Count;
                for (int sourceIndex = 0; sourceIndex < count; sourceIndex++)
                {
                    TSourceItem sourceItem = _sourceAsList[sourceIndex];
                    ItemInfo    itemInfo   = registerSourceItem(sourceItem, sourceIndex);

                    if (ApplyPredicate(sourceIndex))
                    {
                        _predicatePassedCount++;
                        itemInfo.PredicateResult = true;
                    }
                }

                _sourceNotifyCollectionChangedEventHandler = handleSourceCollectionChanged;

                if (_rootSourceWrapper)
                {
                    _sourceAsList.CollectionChanged += _sourceNotifyCollectionChangedEventHandler;
                }
                else
                {
                    _sourceWeakNotifyCollectionChangedEventHandler =
                        new WeakNotifyCollectionChangedEventHandler(_sourceNotifyCollectionChangedEventHandler);

                    _sourceAsList.CollectionChanged += _sourceWeakNotifyCollectionChangedEventHandler.Handle;
                }

                calculateValue();
            }
            else
            {
                if (_value)
                {
                    setValue(false);
                }
            }
        }
Esempio n. 41
0
        /// <summary>
        /// Invokes an action for each item in a collection and subsequently each item added or
        /// removed from the collection.
        /// </summary>
        /// <typeparam name="T">The type of the collection items.</typeparam>
        /// <param name="collection">The collection.</param>
        /// <param name="added">
        /// An action called initially for each item in the collection and subsequently for each
        /// item added to the collection. The parameters passed are the index in the collection and
        /// the item.
        /// </param>
        /// <param name="removed">
        /// An action called for each item removed from the collection. The parameters passed are
        /// the index in the collection and the item.
        /// </param>
        /// <param name="reset">
        /// An action called when the collection is reset. This will be followed by calls to
        /// <paramref name="added"/> for each item present in the collection after the reset.
        /// </param>
        /// <param name="weakSubscription">
        /// Indicates if a weak subscription should be used to track changes to the collection.
        /// </param>
        /// <returns>A disposable used to terminate the subscription.</returns>
        public static IDisposable ForEachItem <T>(
            this IAvaloniaReadOnlyList <T> collection,
            Action <int, T> added,
            Action <int, T> removed,
            Action reset,
            bool weakSubscription = false)
        {
            void Add(int index, IList items)
            {
                foreach (T item in items)
                {
                    added(index++, item);
                }
            }

            void Remove(int index, IList items)
            {
                for (var i = items.Count - 1; i >= 0; --i)
                {
                    removed(index + i, (T)items[i]);
                }
            }

            NotifyCollectionChangedEventHandler handler = (_, e) =>
            {
                switch (e.Action)
                {
                case NotifyCollectionChangedAction.Add:
                    Add(e.NewStartingIndex, e.NewItems);
                    break;

                case NotifyCollectionChangedAction.Move:
                case NotifyCollectionChangedAction.Replace:
                    Remove(e.OldStartingIndex, e.OldItems);
                    Add(e.NewStartingIndex, e.NewItems);
                    break;

                case NotifyCollectionChangedAction.Remove:
                    Remove(e.OldStartingIndex, e.OldItems);
                    break;

                case NotifyCollectionChangedAction.Reset:
                    if (reset == null)
                    {
                        throw new InvalidOperationException(
                                  "Reset called on collection without reset handler.");
                    }

                    reset();
                    Add(0, (IList)collection);
                    break;
                }
            };

            Add(0, (IList)collection);

            if (weakSubscription)
            {
                return(collection.WeakSubscribe(handler));
            }
            else
            {
                collection.CollectionChanged += handler;

                return(Disposable.Create(() => collection.CollectionChanged -= handler));
            }
        }
Esempio n. 42
0
 public ObservableList() : base()
 {
     CollectionChanged += new NotifyCollectionChangedEventHandler(nObservableCollection_CollectionChanged);
 }
Esempio n. 43
0
        void RunView(UIViewType viewType, ViewWithData arg = null)
        {
            if (requestedTarget?.ViewType == viewType || (requestedTarget?.ViewType == UIViewType.None && requestedTarget?.MainFlow == CurrentFlow))
            {
                arg = requestedTarget;
            }

            if (arg == null)
            {
                arg = new ViewWithData {
                    ActiveFlow = activeFlow, MainFlow = selectedFlow, ViewType = viewType
                }
            }
            ;
            bool firstTime = CreateViewAndViewModel(viewType, arg);
            var  view      = GetObjectsForFlow(activeFlow)[viewType].View;

            transition.OnNext(new LoadData
            {
                Flow = activeFlow,
                View = view,
                Data = arg
            });

            // controller might have been stopped in the OnNext above
            if (IsStopped)
            {
                return;
            }

            // if it's not the first time we've shown this view, no need
            // to set it up
            if (!firstTime)
            {
                return;
            }

            SetupView(viewType, view.ViewModel);
        }

        void SetupView(UIViewType viewType, IViewModel viewModel)
        {
            var list      = GetObjectsForFlow(activeFlow);
            var pair      = list[viewType];
            var hasDone   = viewModel as IHasDone;
            var hasCancel = viewModel as IHasCancel;

            // 2FA is set up when login is set up, so nothing to do
            if (viewType == UIViewType.TwoFactor)
            {
                return;
            }

            // we're setting up the login dialog, we need to setup the 2fa as
            // well to continue the flow if it's needed, since the
            // authenticationresult callback won't happen until
            // everything is done
            if (viewType == UIViewType.Login)
            {
                var pair2fa = list[UIViewType.TwoFactor];
                pair2fa.AddHandler(((IDialogViewModel)pair2fa.ViewModel).WhenAny(x => x.IsShowing, x => x.Value)
                                   .Where(x => x)
                                   .ObserveOn(RxApp.MainThreadScheduler)
                                   .Subscribe(_ => Fire(Trigger.Next)));

                pair2fa.AddHandler(((IHasCancel)pair2fa.ViewModel).Cancel
                                   .ObserveOn(RxApp.MainThreadScheduler)
                                   .Subscribe(_ => Fire(uiStateMachine.CanFire(Trigger.Cancel) ? Trigger.Cancel : Trigger.Finish)));

                if (hasDone != null)
                {
                    pair.AddHandler(hasDone.Done
                                    .ObserveOn(RxApp.MainThreadScheduler)
                                    .Subscribe(_ => Fire(Trigger.Finish)));
                }
            }
            else if (hasDone != null)
            {
                pair.AddHandler(hasDone.Done
                                .ObserveOn(RxApp.MainThreadScheduler)
                                .Subscribe(_ => Fire(uiStateMachine.CanFire(Trigger.Next) ? Trigger.Next : Trigger.Finish)));
            }

            if (hasCancel != null)
            {
                pair.AddHandler(hasCancel.Cancel
                                .ObserveOn(RxApp.MainThreadScheduler)
                                .Subscribe(_ => Fire(uiStateMachine.CanFire(Trigger.Cancel) ? Trigger.Cancel : Trigger.Finish)));
            }
        }

        /// <summary>
        /// Creates View/ViewModel instances for the specified <paramref name="viewType"/> if they
        /// haven't been created yet in the current flow
        /// </summary>
        /// <param name="viewType"></param>
        /// <returns>true if the View/ViewModel didn't exist and had to be created</returns>
        bool CreateViewAndViewModel(UIViewType viewType, ViewWithData data = null)
        {
            var list = GetObjectsForFlow(activeFlow);

            if (viewType == UIViewType.Login)
            {
                if (!list.ContainsKey(viewType))
                {
                    var d = factory.CreateViewAndViewModel(UIViewType.TwoFactor);
                    list.Add(UIViewType.TwoFactor, d);
                }
            }

            // 2fa view/viewmodel is created when login is created 'cause login needs the 2fa viewmodel
            // so the only thing we want to do is connect the viewmodel to the view when it's showing
            else if (viewType == UIViewType.TwoFactor)
            {
                var d = list[viewType];
                if (d.View.ViewModel == null)
                {
                    d.ViewModel.Initialize(data);
                    d.View.DataContext = d.ViewModel;
                }
            }

            IUIPair pair      = null;
            var     firstTime = !list.TryGetValue(viewType, out pair);

            if (firstTime)
            {
                pair = factory.CreateViewAndViewModel(viewType);
            }

            pair.ViewModel.Initialize(data);

            if (firstTime)
            {
                pair.View.DataContext = pair.ViewModel;
                list.Add(viewType, pair);
            }

            return(firstTime);
        }

        /// <summary>
        /// Returns the view/viewmodel pair for a given flow
        /// </summary>
        Dictionary <UIViewType, IUIPair> GetObjectsForFlow(UIControllerFlow flow)
        {
            Dictionary <UIViewType, IUIPair> list;

            if (!uiObjects.TryGetValue(flow, out list))
            {
                list = new Dictionary <UIViewType, IUIPair>();
                uiObjects.Add(flow, list);
            }
            return(list);
        }

        void Fire(Trigger next, ViewWithData arg = null)
        {
            Debug.WriteLine("Firing {0} from {1} ({2})", next, uiStateMachine.State, GetHashCode());
            if (triggers.ContainsKey(next))
            {
                uiStateMachine.Fire(triggers[next], arg);
            }
            else
            {
                uiStateMachine.Fire(next);
            }
        }

        UIViewType Go(Trigger trigger)
        {
            return(Go(trigger, activeFlow));
        }

        UIViewType Go(Trigger trigger, UIControllerFlow flow)
        {
            var m = machines[flow];

            Debug.WriteLine("Firing {0} from {1} for flow {2} ({3})", trigger, m.State, flow, GetHashCode());
            m.Fire(trigger);
            return(m.State);
        }

        void Reset()
        {
            if (connectionAdded != null)
            {
                connectionManager.Connections.CollectionChanged -= connectionAdded;
            }
            connectionAdded = null;

            var tr  = transition;
            var cmp = completion;

            transition = null;
            completion = null;
            disposables.Clear();
            tr?.Dispose();
            cmp?.Dispose();
            stopping   = false;
            connection = null;
        }

        bool disposed; // To detect redundant calls
Esempio n. 44
0
        public void Start()
        {
            if (connection != null)
            {
                if (selectedFlow != UIControllerFlow.Authentication)
                {
                    gitHubServiceProvider.AddService(this, connection);
                }
                else // sanity check: it makes zero sense to pass a connection in when calling the auth flow
                {
                    Debug.Assert(false, "Calling the auth flow with a connection makes no sense!");
                }

                connection.Login()
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(_ => { }, () =>
                {
                    Debug.WriteLine("Start ({0})", GetHashCode());
                    Fire(Trigger.Next);
                });
            }
            else
            {
                connectionManager
                .GetLoggedInConnections(hosts)
                .FirstOrDefaultAsync()
                .Select(c =>
                {
                    bool loggedin = c != null;
                    if (selectedFlow != UIControllerFlow.Authentication)
                    {
                        if (loggedin)     // register the first available connection so the viewmodel can use it
                        {
                            connection = c;
                            gitHubServiceProvider.AddService(this, c);
                        }
                        else
                        {
                            // a connection will be added to the list when auth is done, register it so the next
                            // viewmodel can use it
                            connectionAdded = (s, e) =>
                            {
                                if (e.Action == NotifyCollectionChangedAction.Add)
                                {
                                    connection = e.NewItems[0] as IConnection;
                                    if (connection != null)
                                    {
                                        gitHubServiceProvider.AddService(typeof(IConnection), this, connection);
                                    }
                                }
                            };
                            connectionManager.Connections.CollectionChanged += connectionAdded;
                        }
                    }
                    return(loggedin);
                })
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(_ => { }, () =>
                {
                    Debug.WriteLine("Start ({0})", GetHashCode());
                    Fire(Trigger.Next);
                });
            }
        }
 public static IObservable <NotifyCollectionChangedEventArgs> WhenCollectionChanged(this INotifyCollectionChanged collection) => Observable.Create <NotifyCollectionChangedEventArgs>(ob =>
 {
     var handler = new NotifyCollectionChangedEventHandler((sender, args) => ob.OnNext(args));
     collection.CollectionChanged += handler;
     return(() => collection.CollectionChanged -= handler);
 });
 public PropertyNotifier(INotifyCollectionChanged obj, PropertyChangingEventHandler propertyChangingHandler, PropertyChangedEventHandler propertyChangedHandler, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, object newItem, object oldItem, int index, params string[] properties)
 {
     this.collectionChangedObject    = obj;
     this.collectionChangedHandler   = collectionChangedHandler;
     this.collectionChangedEventArgs = new NotifyCollectionChangedEventArgs(action, newItem, oldItem, index);
 }
Esempio n. 47
0
 public DeeplyObservableCollection()
     : base()
 {
     CollectionChanged += new NotifyCollectionChangedEventHandler(DeeplyObservableCollection_CollectionChanged);
 }
Esempio n. 48
0
 /// <summary>
 /// Constructors
 /// </summary>
 public ObservableCollectionEx() : base()
 {
     CollectionChanged += new NotifyCollectionChangedEventHandler(ObservableCollectionEx_CollectionChanged);
 }
 public static PropertyNotifier Notify(this INotifyCollectionChanged obj, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, IList changedItems, int index, int oldIndex)
 {
     return(new PropertyNotifier(obj, collectionChangedHandler, action, changedItems, index, oldIndex));
 }
 public ItemsSourceTableViewSource([NotNull] UITableView tableView,
                                   string itemTemplate = AttachedMemberConstants.ItemTemplate)
     : base(tableView, itemTemplate)
 {
     _weakHandler = ReflectionExtensions.MakeWeakCollectionChangedHandler(this, (adapter, o, arg3) => adapter.OnCollectionChanged(o, arg3));
 }
 public static PropertyNotifier Notify(this INotifyCollectionChanged obj, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, object changedItem)
 {
     return(new PropertyNotifier(obj, collectionChangedHandler, action, changedItem));
 }
Esempio n. 52
0
        private void initializeFromSources()
        {
            if (_outerSourceNotifyCollectionChangedEventHandler != null)
            {
                _outerSource.CollectionChanged -= _outerSourceWeakNotifyCollectionChangedEventHandler.Handle;
                _outerSourceNotifyCollectionChangedEventHandler     = null;
                _outerSourceWeakNotifyCollectionChangedEventHandler = null;
            }

            if (_innerSourceNotifyCollectionChangedEventHandler != null)
            {
                _innerSource.CollectionChanged -= _innerSourceWeakNotifyCollectionChangedEventHandler.Handle;
                _innerSourceNotifyCollectionChangedEventHandler     = null;
                _innerSourceWeakNotifyCollectionChangedEventHandler = null;
            }

            if (_innerSourceAsINotifyPropertyChanged != null)
            {
                _innerSourceAsINotifyPropertyChanged.PropertyChanged -=
                    _innerSourceWeakPropertyChangedEventHandler.Handle;

                _innerSourceAsINotifyPropertyChanged        = null;
                _innerSourcePropertyChangedEventHandler     = null;
                _innerSourceWeakPropertyChangedEventHandler = null;
            }

            if (_outerSourceAsINotifyPropertyChanged != null)
            {
                _outerSourceAsINotifyPropertyChanged.PropertyChanged -=
                    _outerSourceWeakPropertyChangedEventHandler.Handle;

                _outerSourceAsINotifyPropertyChanged        = null;
                _outerSourcePropertyChangedEventHandler     = null;
                _outerSourceWeakPropertyChangedEventHandler = null;
            }


            if (_outerSource != null || _innerSource != null)
            {
                baseClearItems();
            }

            if (_outerSourceScalar != null)
            {
                _outerSource = _outerSourceScalar.Value;
            }
            _outerSourceAsList = (IList <TOuterSourceItem>)_outerSource;

            if (_innerSourceScalar != null)
            {
                _innerSource = _innerSourceScalar.Value;
            }
            _innerSourceAsList = (IList <TInnerSourceItem>)_innerSource;

            if (_outerSource != null && _innerSource != null)
            {
                _outerSourceAsObservableCollectionWithChangeMarker = _outerSourceAsList as ObservableCollectionWithChangeMarker <TOuterSourceItem>;

                if (_outerSourceAsObservableCollectionWithChangeMarker != null)
                {
                    _lastProcessedOuterSourceChangeMarker = _outerSourceAsObservableCollectionWithChangeMarker.ChangeMarkerField;
                }
                else
                {
                    _outerSourceAsINotifyPropertyChanged = (INotifyPropertyChanged)_outerSource;

                    _outerSourcePropertyChangedEventHandler = (sender, args) =>
                    {
                        if (args.PropertyName == "Item[]")
                        {
                            _outerSourceIndexerPropertyChangedEventRaised = true;                                                        // ObservableCollection raises this before CollectionChanged event raising
                        }
                    };

                    _outerSourceWeakPropertyChangedEventHandler =
                        new WeakPropertyChangedEventHandler(_outerSourcePropertyChangedEventHandler);

                    _outerSourceAsINotifyPropertyChanged.PropertyChanged +=
                        _outerSourceWeakPropertyChangedEventHandler.Handle;
                }


                _innerSourceAsObservableCollectionWithChangeMarker = _innerSourceAsList as ObservableCollectionWithChangeMarker <TInnerSourceItem>;

                if (_innerSourceAsObservableCollectionWithChangeMarker != null)
                {
                    _lastProcessedInnerSourceChangeMarker = _innerSourceAsObservableCollectionWithChangeMarker.ChangeMarkerField;
                }
                else
                {
                    _innerSourceAsINotifyPropertyChanged = (INotifyPropertyChanged)_innerSource;

                    _innerSourcePropertyChangedEventHandler = (sender, args) =>
                    {
                        if (args.PropertyName == "Item[]")
                        {
                            _innerSourceIndexerPropertyChangedEventRaised = true;                                                        // ObservableCollection raises this before CollectionChanged event raising
                        }
                    };

                    _innerSourceWeakPropertyChangedEventHandler =
                        new WeakPropertyChangedEventHandler(_innerSourcePropertyChangedEventHandler);

                    _innerSourceAsINotifyPropertyChanged.PropertyChanged +=
                        _innerSourceWeakPropertyChangedEventHandler.Handle;
                }


                // ReSharper disable once PossibleNullReferenceException
                int outerSourceCount = _outerSourceAsList.Count;
                // ReSharper disable once PossibleNullReferenceException
                int innerSourceCount = _innerSourceAsList.Count;
                int baseIndex        = 0;
                for (int outerSourceIndex = 0; outerSourceIndex < outerSourceCount; outerSourceIndex++)
                {
                    TOuterSourceItem sourceOuterItem = _outerSourceAsList[outerSourceIndex];
                    for (int innerSourceIndex = 0; innerSourceIndex < innerSourceCount; innerSourceIndex++)
                    {
                        TInnerSourceItem sourceInnerItem = _innerSourceAsList[innerSourceIndex];
                        JoinPair <TOuterSourceItem, TInnerSourceItem> joinPair = new JoinPair <TOuterSourceItem, TInnerSourceItem>(
                            sourceOuterItem, sourceInnerItem);
                        baseInsertItem(baseIndex + innerSourceIndex, joinPair);
                    }

                    baseIndex = baseIndex + innerSourceCount;
                }

                _outerSourceNotifyCollectionChangedEventHandler     = handleOuterSourceCollectionChanged;
                _outerSourceWeakNotifyCollectionChangedEventHandler =
                    new WeakNotifyCollectionChangedEventHandler(_outerSourceNotifyCollectionChangedEventHandler);

                _outerSource.CollectionChanged += _outerSourceWeakNotifyCollectionChangedEventHandler.Handle;

                _innerSourceNotifyCollectionChangedEventHandler     = handleInnerSourceCollectionChanged;
                _innerSourceWeakNotifyCollectionChangedEventHandler =
                    new WeakNotifyCollectionChangedEventHandler(_innerSourceNotifyCollectionChangedEventHandler);

                _innerSource.CollectionChanged += _innerSourceWeakNotifyCollectionChangedEventHandler.Handle;
            }
        }
 public PropertyNotifier(INotifyCollectionChanged obj, PropertyChangingEventHandler propertyChangingHandler, PropertyChangedEventHandler propertyChangedHandler, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, IList changedItems, int startingIndex, params string[] properties)
 {
     this.collectionChangedObject    = obj;
     this.collectionChangedHandler   = collectionChangedHandler;
     this.collectionChangedEventArgs = new NotifyCollectionChangedEventArgs(action, changedItems, startingIndex);
 }
 public VisualElementTracker()
 {
     _collectionChangedHandler = ModelGestureRecognizersOnCollectionChanged;
 }
 public PropertyNotifier(INotifyCollectionChanged obj, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex)
 {
     this.collectionChangedObject    = obj;
     this.collectionChangedHandler   = collectionChangedHandler;
     this.collectionChangedEventArgs = new NotifyCollectionChangedEventArgs(action, newItems, oldItems, startingIndex);
 }
Esempio n. 56
0
        public void CustomCollectionTest()
        {
            var originalCollection = new CustomCollection <MyModel>(true)
            {
                new MyModel(),
                new MyModel(),
                new MyModel()
            };

            using var synchronizingCollection = new SynchronizingCollectionCore <MyDataModel, MyModel>(
                      originalCollection, m => new MyDataModel(m));
            AssertHelper.SequenceEqual(originalCollection, synchronizingCollection.Select(dm => dm.Model));

            // Check add operation with collection changed event.
            bool handlerCalled = false;
            NotifyCollectionChangedEventHandler handler = (sender, e) =>
            {
                handlerCalled = true;
                Assert.AreEqual(synchronizingCollection, sender);
                Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action);
                Assert.AreEqual(3, e.NewStartingIndex);
                Assert.AreEqual(originalCollection.Last(), e.NewItems.Cast <MyDataModel>().Single().Model);
            };

            synchronizingCollection.CollectionChanged += handler;
            originalCollection.Add(new MyModel());
            synchronizingCollection.CollectionChanged -= handler;
            Assert.IsTrue(handlerCalled);

            // Compare the collections
            AssertHelper.SequenceEqual(originalCollection, synchronizingCollection.Select(dm => dm.Model));

            // Check remove operation with collection changed event.
            MyModel itemToRemove = originalCollection[2];

            handlerCalled = false;
            handler       = (sender, e) =>
            {
                handlerCalled = true;
                Assert.AreEqual(synchronizingCollection, sender);
                Assert.AreEqual(NotifyCollectionChangedAction.Remove, e.Action);
                Assert.AreEqual(2, e.OldStartingIndex);
                Assert.AreEqual(itemToRemove, e.OldItems.Cast <MyDataModel>().Single().Model);
            };
            synchronizingCollection.CollectionChanged += handler;
            originalCollection.Remove(itemToRemove);
            synchronizingCollection.CollectionChanged -= handler;
            Assert.IsTrue(handlerCalled);

            // Check replace operation with collection changed event.
            MyModel itemToReplace      = originalCollection[1];
            int     handlerCalledCount = 0;

            handler = (sender, e) =>
            {
                Assert.AreEqual(synchronizingCollection, sender);
                if (handlerCalledCount == 0)
                {
                    Assert.AreEqual(NotifyCollectionChangedAction.Remove, e.Action);
                    Assert.AreEqual(itemToReplace, e.OldItems.Cast <MyDataModel>().Single().Model);
                }
                else
                {
                    Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action);
                    Assert.AreEqual(originalCollection[1], e.NewItems.Cast <MyDataModel>().Single().Model);
                }
                handlerCalledCount++;
            };
            synchronizingCollection.CollectionChanged += handler;
            originalCollection[1] = new MyModel();
            synchronizingCollection.CollectionChanged -= handler;
            Assert.AreEqual(2, handlerCalledCount);

            // Check reset operation with collection changed event.
            var newItems = new List <MyModel>()
            {
                new MyModel(),
                new MyModel()
            };

            handlerCalledCount = 0;
            handler            = (sender, e) =>
            {
                Assert.AreEqual(synchronizingCollection, sender);
                if (handlerCalledCount == 0)
                {
                    Assert.AreEqual(NotifyCollectionChangedAction.Reset, e.Action);
                }
                else
                {
                    Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action);
                }
                handlerCalledCount++;
            };
            synchronizingCollection.CollectionChanged += handler;
            originalCollection.Reset(newItems);
            synchronizingCollection.CollectionChanged -= handler;
            Assert.AreEqual(3, handlerCalledCount);
            AssertHelper.SequenceEqual(newItems, synchronizingCollection.Select(dm => dm.Model));
        }
Esempio n. 57
0
        public void ObservableCollectionTest()
        {
            var originalCollection = new ObservableCollection <MyModel>()
            {
                new MyModel(),
                new MyModel(),
                new MyModel()
            };

            using var synchronizingCollection = new SynchronizingCollectionCore <MyDataModel, MyModel>(originalCollection, m => new MyDataModel(m));
            AssertHelper.SequenceEqual(originalCollection, synchronizingCollection.Select(dm => dm.Model));

            // Check add operation with collection changed event.
            bool handlerCalled = false;
            NotifyCollectionChangedEventHandler handler = (sender, e) =>
            {
                handlerCalled = true;
                Assert.AreEqual(synchronizingCollection, sender);
                Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action);
                Assert.AreEqual(3, e.NewStartingIndex);
                Assert.AreEqual(originalCollection.Last(), e.NewItems.Cast <MyDataModel>().Single().Model);
            };

            synchronizingCollection.CollectionChanged += handler;
            originalCollection.Add(new MyModel());
            synchronizingCollection.CollectionChanged -= handler;
            Assert.IsTrue(handlerCalled);

            // Check insert at index 0 operation with collection changed event.
            handlerCalled = false;
            handler       = (sender, e) =>
            {
                handlerCalled = true;
                Assert.AreEqual(synchronizingCollection, sender);
                Assert.AreEqual(NotifyCollectionChangedAction.Add, e.Action);
                Assert.AreEqual(0, e.NewStartingIndex);
                Assert.AreEqual(originalCollection[0], e.NewItems.Cast <MyDataModel>().Single().Model);
            };
            synchronizingCollection.CollectionChanged += handler;
            originalCollection.Insert(0, new MyModel());
            synchronizingCollection.CollectionChanged -= handler;
            Assert.IsTrue(handlerCalled);

            // Compare the collections
            AssertHelper.SequenceEqual(originalCollection, synchronizingCollection.Select(dm => dm.Model));

            // Check remove operation with collection changed event.
            MyModel itemToRemove = originalCollection[2];

            handlerCalled = false;
            handler       = (sender, e) =>
            {
                handlerCalled = true;
                Assert.AreEqual(synchronizingCollection, sender);
                Assert.AreEqual(NotifyCollectionChangedAction.Remove, e.Action);
                Assert.AreEqual(2, e.OldStartingIndex);
                Assert.AreEqual(itemToRemove, e.OldItems.Cast <MyDataModel>().Single().Model);
            };
            synchronizingCollection.CollectionChanged += handler;
            originalCollection.Remove(itemToRemove);
            synchronizingCollection.CollectionChanged -= handler;
            Assert.IsTrue(handlerCalled);

            // Check replace operation with collection changed event.
            MyModel itemToReplace = originalCollection[1];

            handlerCalled = false;
            handler       = (sender, e) =>
            {
                handlerCalled = true;
                Assert.AreEqual(synchronizingCollection, sender);
                Assert.AreEqual(NotifyCollectionChangedAction.Replace, e.Action);
                Assert.AreEqual(1, e.NewStartingIndex);
                Assert.AreEqual(1, e.OldStartingIndex);
                Assert.AreEqual(originalCollection[1], e.NewItems.Cast <MyDataModel>().Single().Model);
                Assert.AreEqual(itemToReplace, e.OldItems.Cast <MyDataModel>().Single().Model);
            };
            synchronizingCollection.CollectionChanged += handler;
            originalCollection[1] = new MyModel();
            synchronizingCollection.CollectionChanged -= handler;
            Assert.IsTrue(handlerCalled);

            // Check move operation with collection changed event.
            handlerCalled = false;
            handler       = (sender, e) =>
            {
                handlerCalled = true;
                Assert.AreEqual(synchronizingCollection, sender);
                Assert.AreEqual(NotifyCollectionChangedAction.Move, e.Action);
                Assert.AreEqual(0, e.OldStartingIndex);
                Assert.AreEqual(2, e.NewStartingIndex);
            };
            synchronizingCollection.CollectionChanged += handler;
            originalCollection.Move(0, 2);
            synchronizingCollection.CollectionChanged -= handler;
            Assert.IsTrue(handlerCalled);

            // Check clear operation with collection changed event.
            handlerCalled = false;
            handler       = (sender, e) =>
            {
                handlerCalled = true;
                Assert.AreEqual(synchronizingCollection, sender);
                Assert.AreEqual(NotifyCollectionChangedAction.Reset, e.Action);
            };
            synchronizingCollection.CollectionChanged += handler;
            originalCollection.Clear();
            synchronizingCollection.CollectionChanged -= handler;
            Assert.IsTrue(handlerCalled);
            Assert.IsFalse(synchronizingCollection.Any());
        }
Esempio n. 58
0
 public static PropertyNotifier Notify(this INotifyCollectionChanged obj, PropertyChangingEventHandler propertyChangingHandler, PropertyChangedEventHandler propertyChangedHandler, NotifyCollectionChangedEventHandler collectionChangedHandler, NotifyCollectionChangedAction action, IList changedItems, int index, int oldIndex, params string[] properties)
 {
     return(new PropertyNotifier(obj, propertyChangingHandler, propertyChangedHandler, collectionChangedHandler, action, changedItems.Cast <object>().ToList(), index, oldIndex, properties));
 }
Esempio n. 59
0
 protected ItemsSourceGeneratorBase()
 {
     _handler = ReflectionExtensions.MakeWeakCollectionChangedHandler(this, (@base, o, arg3) => @base.OnCollectionChanged(arg3));
 }
Esempio n. 60
0
 public ObservableCollectionEx(IEnumerable <T> l) : base(l)
 {
     CollectionChanged += new NotifyCollectionChangedEventHandler(ObservableCollectionEx_CollectionChanged);
 }