public OverviewMapController(MapView overview)
        {
            _insetView     = overview;
            _extentOverlay = new GraphicsOverlay();
            if (_insetView.GraphicsOverlays == null)
            {
                _insetView.GraphicsOverlays = new GraphicsOverlayCollection();
            }

            _insetView.GraphicsOverlays.Add(_extentOverlay);

            _extentGraphic = new Graphic();
            _extentOverlay.Graphics.Add(_extentGraphic);

            // _overview.ViewpointChanged += OnViewpointChanged
            _viewpointListener = new WeakEventListener <GeoView, object?, EventArgs>(_insetView)
            {
                OnEventAction  = (instance, source, eventArgs) => OnInsetViewpointChanged(source, eventArgs),
                OnDetachAction = (instance, weakEventListener) => instance.ViewpointChanged -= weakEventListener.OnEvent,
            };
            _insetView.ViewpointChanged += _viewpointListener.OnEvent;

            // _overview.NavigationCompleted += OnNavigationCompleted;
            _navigationListener = new WeakEventListener <GeoView, object?, EventArgs>(_insetView)
            {
                OnEventAction  = (instance, source, eventArgs) => OnInsetNavigationCompleted(source, eventArgs),
                OnDetachAction = (instance, weakEventListener) => instance.NavigationCompleted -= weakEventListener.OnEvent,
            };
            _insetView.NavigationCompleted += _navigationListener.OnEvent;
        }
        private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
        {
            // Remove handler for oldValue.CollectionChanged (if present)
            INotifyCollectionChanged oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;

            if (null != oldValueINotifyCollectionChanged && null != _collectionChangedWeakEventListener)
            {
                _collectionChangedWeakEventListener.Detach();
                _collectionChangedWeakEventListener = null;
            }

            // Add handler for newValue.CollectionChanged (if possible)
            INotifyCollectionChanged newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;

            if (null != newValueINotifyCollectionChanged)
            {
                _collectionChangedWeakEventListener = new WeakEventListener <MultiCircleChart, object, NotifyCollectionChangedEventArgs>(this);
                _collectionChangedWeakEventListener.OnEventAction   = (instance, source, eventArgs) => instance.ItemsSourceCollectionChanged(source, eventArgs);
                _collectionChangedWeakEventListener.OnDetachAction  = (weakEventListener) => newValueINotifyCollectionChanged.CollectionChanged -= weakEventListener.OnEvent;
                newValueINotifyCollectionChanged.CollectionChanged += _collectionChangedWeakEventListener.OnEvent;
            }

            // Store a local cached copy of the data
            _items = newValue == null ? null : new List <object>(newValue.Cast <object>().ToList());

            //// Clear and set the view on the selection adapter
            RefreshView();
        }
        public SpreadsheetCellDataFieldViewModel(Type viewModelType, PropertyInfo propertyInfo, IEditableProxy model, DetailsViewModel parentViewModel, IColumnItem column)
        {            
            _propertyInfo = propertyInfo;            
            _parentModel = model;
            if (_parentModel != null)
            {                
                var parentModelBO = _parentModel as BusinessBase;
                if (parentModelBO != null)
                {
                    var weakListener = new WeakEventListener<SpreadsheetCellDataFieldViewModel, BusinessBase, PropertyChangedEventArgs>(this, parentModelBO);

                    parentModelBO.PropertyChanged += weakListener.OnEvent;
                    weakListener.OnEventAction += OnParentModelPropertyChanged;
                    weakListener.OnDetachAction += Static;
                }

                _allProperties = _parentModel.GetAllPropertiesForInstance();
                var root = _parentModel.GetModel();
                if (root != null)
                    _allMasterProperties = root.GetAllPropertiesForInstance();                
            }

            _parentDetailsVM = parentViewModel;
            _fieldViewModelType = viewModelType;
            _column = column;
        }
        public CollectionView(IEnumerable collection)
        {
            _sourceCollection = collection ?? throw new ArgumentNullException("collection");

            // forward collection change events from underlying collection to our listeners.
            INotifyCollectionChanged incc = collection as INotifyCollectionChanged;

            if (incc != null)
            {
                _sourceWeakEventListener =
                    new WeakEventListener <CollectionView, object, NotifyCollectionChangedEventArgs>(this)
                {
                    // Call the actual collection changed event
                    OnEventAction = (source, changed, arg) => OnCollectionChanged(source, arg),

                    // The source doesn't exist anymore
                    OnDetachAction = (listener) => incc.CollectionChanged -= _sourceWeakEventListener.OnEvent
                };
                incc.CollectionChanged += _sourceWeakEventListener.OnEvent;
            }

            _currentItem     = null;
            _currentPosition = -1;
            SetFlag(CollectionViewFlags.IsCurrentBeforeFirst, _currentPosition < 0);
            SetFlag(CollectionViewFlags.IsCurrentAfterLast, _currentPosition < 0);
            SetFlag(CollectionViewFlags.CachedIsEmpty, _currentPosition < 0);
        }
Beispiel #5
0
		private static void AttachObservableModelCallback(DependencyObject source, DependencyPropertyChangedEventArgs args)
		{
			var typeName = args.NewValue as string;
			var view = source as FrameworkElement;
			if (typeName == null || view == null)
				return;

			var modelType = Type.GetType("Raven.Studio.Models." + typeName) ?? Type.GetType(typeName);
			if (modelType == null)
				return;

			try
			{
				var model = (Model)Activator.CreateInstance(modelType);
				model.ForceTimerTicked();

				var observable = (IObservable)Activator.CreateInstance(typeof(Observable<>).MakeGenericType(modelType));
				observable.Value = model;
				view.DataContext = observable;

				SetPageTitle(model, view);
				
				var weakListener = new WeakEventListener<IObservable, object, RoutedEventArgs>(observable);
				view.Loaded += weakListener.OnEvent;
				weakListener.OnEventAction = OnViewLoaded;
				weakListener.OnDetachAction = listener => view.Loaded -= listener.OnEvent;
			}
			catch (Exception ex)
			{
				throw new InvalidOperationException(string.Format("Cannot create instance of model type: {0}", modelType), ex);
			}
		}
        public TransitMap()
        {
            this.InitializeComponent();
            MainMap.MapServiceToken = Keys.BingMapKey;
            CenterConverter.Add(new LatLonTransformConverter()
            {
                Transform = ll => CenterOffset.IsNotALocation ? ll : ll + CenterOffset, ReverseTransform = ll => CenterOffset.IsNotALocation ? ll : ll - CenterOffset
            });
            CenterConverter.Add(LatLonToGeopointConverter.Instance);
            WeakEventListener <TransitMap, object, NotifyCollectionChangedEventArgs> addInsListener = new WeakEventListener <TransitMap, object, NotifyCollectionChangedEventArgs>(this);

            addInsListener.OnEventAction = (map, obj, e) => map.AddIns_CollectionChanged(obj, e);
            AddIns.CollectionChanged    += addInsListener.OnEvent;

            MapRouteBindings    = new CompositeCollectionBinding <MapRouteView, TransitMapAddInBase>(MainMap.Routes);
            MapElementBindings  = new CompositeCollectionBinding <MapElement, TransitMapAddInBase>(MainMap.MapElements);
            MapChildrenBindings = new CompositeCollectionBinding <DependencyObject, TransitMapAddInBase>(MainMap.Children);

            //MainMap.SetBinding(MapControl.CenterProperty, new Binding() { Converter = CenterConverters, Source = this, Path = new PropertyPath("Center"), Mode = BindingMode.TwoWay });
            //MainMap.SetBinding(MapControl.ZoomLevelProperty, new Binding() { Source = this, Path = new PropertyPath("ZoomLevel"), Mode = BindingMode.TwoWay });

            //MapIcon centerIndicator = new MapIcon() { NormalizedAnchorPoint = new Point(0.5, 1) };
            //BindingOperations.SetBinding(centerIndicator, MapIcon.LocationProperty, new Binding() { Source = this, Path = new PropertyPath("Center"), Converter = LatLonToGeopointConverter.Instance });
            //MainMap.MapElements.Add(centerIndicator);
        }
Beispiel #7
0
        private static void Detach([NotNull] WeakEventListener <ObservableFilteredCollection <T>, INotifyCollectionChanged, NotifyCollectionChangedEventArgs> weakEvent, [NotNull] INotifyCollectionChanged sender)
        {
            Contract.Requires(weakEvent != null);
            Contract.Requires(sender != null);

            sender.CollectionChanged -= weakEvent.OnEvent;
        }
        private void AttachLayersHandler(IEnumerable <Layer> layers)
        {
            if (layers != null)
            {
                // Subscribe to Layers Collection changes
                var layersINotifyCollectionChanged = layers as INotifyCollectionChanged;
                if (layersINotifyCollectionChanged != null)
                {
                    Debug.Assert(_layersWeakEventListener == null);
                    _layersWeakEventListener = new WeakEventListener <TemplatePicker, object, NotifyCollectionChangedEventArgs>(this)
                    {
                        OnEventAction  = (instance, source, eventArgs) => instance.OnLayerCollectionChanged(source, eventArgs),
                        OnDetachAction = weakEventListener => layersINotifyCollectionChanged.CollectionChanged -= weakEventListener.OnEvent
                    };
                    layersINotifyCollectionChanged.CollectionChanged += _layersWeakEventListener.OnEvent;
                }

                // Subscribe to FeatureLayers Property Changes
                Debug.Assert(_featureLayerPropertyChangedListeners == null);
                _featureLayerPropertyChangedListeners = new DependencyPropertyChangedListeners <TemplatePicker>(this)
                {
                    OnEventAction = (instance, source, eventArgs) => instance.OnLayerPropertyChanged(source, eventArgs)
                };

                foreach (var layer in layers.OfType <FeatureLayer>())
                {
                    AttachLayerHandler(layer);
                }
            }
        }
        private static void Attach([NotNull] WeakEventListener <ObservableWrappedCollection <TSource, TTarget>, INotifyCollectionChanged, NotifyCollectionChangedEventArgs> weakEvent, [NotNull] INotifyCollectionChanged sender)
        {
            Contract.Requires(weakEvent != null);
            Contract.Requires(sender != null);

            sender.CollectionChanged += weakEvent.OnEvent;
        }
Beispiel #10
0
            public void DoesNotLeakWithActionsDefinedInDisplayClass()
            {
                var source = new EventSource();

                var counter = 0;

                Action action = () =>
                {
                    counter++;
                };

                var weakEventListener = WeakEventListener.SubscribeToWeakEvent(this, source, "PublicEvent", action);

                Assert.AreEqual(0, counter);

                source.RaisePublicEvent();

                Assert.AreEqual(1, counter);

                // Some dummy code to make sure the previous listener is removed
                GC.Collect();

                //Assert.IsTrue(weakEventListener.IsSourceAlive);
                //Assert.IsFalse(weakEventListener.IsTargetAlive);

                // Some dummy code to make sure the source stays in memory
                source.GetType();
            }
        public virtual void Initialize(ChecklistSingleViewModel parentVM, IFieldDefinitionEntity fieldDef, IEventAggregator eventAggregator)
        {
            _eventAggregator = eventAggregator;

            _process = (TemplateEntity)parentVM.QuestionsTemplate;
            _parentVM = parentVM;
            _fieldDefinition = fieldDef;
            ChangeChartTypeCommand = new DelegateCommand(ExecuteChange);

            PrepareFieldDefRelatedData();

            var weakListener = new WeakEventListener<SPCChartControlViewModel, ChecklistViewModelBase, EventArgs>(this, parentVM);
            parentVM.SelectesQuestionChanged += weakListener.OnEvent;
            weakListener.OnEventAction = OnSelectedQuestionChanged;
            weakListener.OnDetachAction = (listener, source) =>
            {
                source.SelectesQuestionChanged -= listener.OnEvent;
            };

            ShowLCLAnyChart = true; ShowUCLAnyChart = true; ShowMeanAnyChart = true;
            ShowLCLRangeChart = true; ShowUCLRangeChart = true; ShowMeanRangeChart = true;
            ShowUSL = false; ShowLSL = false;

            OnSelectedQuestionChanged(this, parentVM, EventArgs.Empty);            
        }
        public void AfterListenerIsNull_EventDetaching()
        {
            WasDetached = false;
            EventCounter = 0;

            var list = new ObservableCollection<int>();

            WeakEventListener<object, ObservableCollection<int>, EventArgs> weakEventListener = null;

            var obj = new object();

            weakEventListener = new WeakEventListener<object, ObservableCollection<int>, EventArgs>(obj, list);

            list.CollectionChanged += weakEventListener.OnEvent;
            weakEventListener.OnEventAction += (o, o1, arg3) =>
                {
                    EventCounter++;
                };
            weakEventListener.OnDetachAction += (listener, source) =>
                {
                    source.CollectionChanged -= listener.OnEvent;
                    WasDetached = true;
                };

            list.Add(1);
            obj = null;
            GC.Collect();

            list.Add(2);
            GC.Collect();

            Assert.IsTrue(WasDetached);
            Assert.AreEqual(EventCounter, 1);
        }
Beispiel #13
0
        /// <summary>
        /// Called when the value of the ItemsSourceProperty property changes.
        /// </summary>
        /// <param name="oldValue">The old ItemsSource collection.</param>
        /// <param name="newValue">The new ItemsSource collection.</param>
        protected virtual void OnItemsSourcePropertyChanged(IEnumerable oldValue, IEnumerable newValue)
        {
            // Remove handler for oldValue.CollectionChanged (if present)
            INotifyCollectionChanged oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;

            if (null != oldValueINotifyCollectionChanged)
            {
                // Detach the WeakEventListener
                if (null != _weakEventListener)
                {
                    _weakEventListener.Detach();
                    _weakEventListener = null;
                }
            }

            // Add handler for newValue.CollectionChanged (if possible)
            INotifyCollectionChanged newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;

            if (null != newValueINotifyCollectionChanged)
            {
                // Use a WeakEventListener so that the backwards reference doesn't keep this object alive
                _weakEventListener = new WeakEventListener <TreeMap, object, NotifyCollectionChangedEventArgs>(this);
                _weakEventListener.OnEventAction  = (instance, source, eventArgs) => instance.ItemsSourceCollectionChanged(source, eventArgs);
                _weakEventListener.OnDetachAction = (weakEventListener) => newValueINotifyCollectionChanged.CollectionChanged -= weakEventListener.OnEvent;
                newValueINotifyCollectionChanged.CollectionChanged += _weakEventListener.OnEvent;
            }

            // Handle property change
            RebuildTree();
        }
Beispiel #14
0
            private static void Detach([NotNull] WeakEventListener <ObservableSelectImpl <TSource, TTarget>, INotifyPropertyChanged, PropertyChangedEventArgs> weakEvent, [NotNull] INotifyPropertyChanged sender)
            {
                Contract.Requires(weakEvent != null);
                Contract.Requires(sender != null);

                sender.PropertyChanged -= weakEvent.OnEvent;
            }
        private void OnCollectionChanged(object oldValue, object newValue)
        {
            if (oldValue is INotifyCollectionChanged)
            {
                var incc = (INotifyCollectionChanged)oldValue;
                incc.CollectionChanged -= Incc_CollectionChanged;
                _inccWeakEventListener?.Detach();
                _inccWeakEventListener = null;
            }

            if (newValue is IEnumerable)
            {
                if (newValue is INotifyCollectionChanged)
                {
                    var incc = (INotifyCollectionChanged)newValue;
                    _inccWeakEventListener = new WeakEventListener <RotatorTile, object, NotifyCollectionChangedEventArgs>(this)
                    {
                        OnEventAction  = (instance, source, eventArgs) => instance.Incc_CollectionChanged(source, eventArgs),
                        OnDetachAction = (listener) => incc.CollectionChanged -= listener.OnEvent
                    };
                    incc.CollectionChanged += _inccWeakEventListener.OnEvent;
                }

                Start();
            }
            else
            {
                _timer?.Stop();
            }
        }
        /// <summary>
        /// Handles changes to the ItemsSource property.
        /// </summary>
        /// <param name="oldValue">Old value.</param>
        /// <param name="newValue">New value.</param>
        private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
        {
            // Remove handler for oldValue.CollectionChanged (if present)
            INotifyCollectionChanged oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;

            if (null != oldValueINotifyCollectionChanged)
            {
                // Detach the WeakEventListener
                if (null != _weakEventListener)
                {
                    _weakEventListener.Detach();
                    _weakEventListener = null;
                }
            }

            // Add handler for newValue.CollectionChanged (if possible)
            INotifyCollectionChanged newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;

            if (null != newValueINotifyCollectionChanged)
            {
                // Use a WeakEventListener so that the backwards reference doesn't keep this object alive
                _weakEventListener = new WeakEventListener <SeriesDefinition, object, NotifyCollectionChangedEventArgs>(this);
                _weakEventListener.OnEventAction  = (instance, source, eventArgs) => instance.ItemsSourceCollectionChanged(source, eventArgs);
                _weakEventListener.OnDetachAction = (weakEventListener) => newValueINotifyCollectionChanged.CollectionChanged -= weakEventListener.OnEvent;
                newValueINotifyCollectionChanged.CollectionChanged += _weakEventListener.OnEvent;
            }

            if (null != ParentDefinitionSeries)
            {
                ParentDefinitionSeries.SeriesDefinitionItemsSourceChanged(this, oldValue, newValue);
            }
        }
        private void Handler()
        {
            var propertyChangedListener = new WeakEventListener<PopUpSearchView, ListBox, SelectionChangedEventArgs>(this, ListBoxItems);

            ListBoxItems.SelectionChanged += propertyChangedListener.OnEvent;
            propertyChangedListener.OnEventAction += ValuePropertyChanged;
            propertyChangedListener.OnDetachAction += Static;
        }
 private void DetachDisposedListener()
 {
     if (_disposedListener != null)
     {
         _disposedListener.Detach();
         _disposedListener = null;
     }
 }
Beispiel #19
0
 internal void ReleaseEvents()
 {
     if (_innerListListener is not null)
     {
         CollectionChangedEventManager.RemoveListener((INotifyCollectionChanged)_innerList, _innerListListener);
         _innerListListener = null;
     }
 }
 private void UnregisterSelectedStopsSourceHandlers(ObservableCollection <TransitStop> collection)
 {
     if (SelectedStopsSource_CollectionChanged_Listener != null)
     {
         SelectedStopsSource_CollectionChanged_Listener.Detach();
         SelectedStopsSource_CollectionChanged_Listener = null;
     }
 }
 internal void ReleaseEvents()
 {
   if( _innerListListener != null )
   {
     CollectionChangedEventManager.RemoveListener( ( INotifyCollectionChanged )_innerList, _innerListListener );
     _innerListListener = null;
   }
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="SelectCrossRefViewModel"/> class.
        /// </summary>
        public SelectCrossRefViewModel()
        {
            CloseOnReturn = false;

            var weakListener = new WeakEventListener<SelectCrossRefViewModel, ObservableCollection<object>, NotifyCollectionChangedEventArgs>(this, _selectedItems);
            _selectedItems.CollectionChanged += weakListener.OnEvent;
            weakListener.OnEventAction += SelectedItemsOnCollectionChanged;
            weakListener.OnDetachAction += Static;
        }
 private void UnregisterStopsSourceHandlers(ObservableCollection <TransitStop> collection)
 {
     if (StopsSource_CollectionChanged_Listener != null)
     {
         collection.CollectionChanged -= StopsSource_CollectionChanged_Listener.OnEvent;
         StopsSource_CollectionChanged_Listener?.Detach();
         StopsSource_CollectionChanged_Listener = null;
     }
 }
 private void UnsubscribeToDpiChanged()
 {
     if (_dpiChangedWeakEventListener != null)
     {
         var dpiChangedListener = _dpiChangedWeakEventListener;
         _dpiChangedWeakEventListener = null;
         CompatUtility.ExecuteOnUIThread(dpiChangedListener.Detach, Dispatcher);
     }
 }
Beispiel #25
0
        private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var obj = (IsNullOrEmptyStateTrigger)d;
            var val = e.NewValue;

            obj.SetActive(IsNullOrEmpty(val));

            if (val == null)
            {
                return;
            }

            // Try to listen for various notification events
            // Starting with INorifyCollectionChanged
            var valNotifyCollection = val as INotifyCollectionChanged;

            if (valNotifyCollection != null)
            {
                var weakEvent = new WeakEventListener <INotifyCollectionChanged, object, NotifyCollectionChangedEventArgs>(valNotifyCollection)
                {
                    OnEventAction  = (instance, source, args) => obj.SetActive(IsNullOrEmpty(instance)),
                    OnDetachAction = (weakEventListener) => valNotifyCollection.CollectionChanged -= weakEventListener.OnEvent
                };

                valNotifyCollection.CollectionChanged += weakEvent.OnEvent;
                return;
            }

            // Not INotifyCollectionChanged, try IObservableVector
            var valObservableVector = val as IObservableVector <object>;

            if (valObservableVector != null)
            {
                var weakEvent = new WeakEventListener <IObservableVector <object>, object, IVectorChangedEventArgs>(valObservableVector)
                {
                    OnEventAction  = (instance, source, args) => obj.SetActive(IsNullOrEmpty(instance)),
                    OnDetachAction = (weakEventListener) => valObservableVector.VectorChanged -= weakEventListener.OnEvent
                };

                valObservableVector.VectorChanged += weakEvent.OnEvent;
                return;
            }

            // Not INotifyCollectionChanged, try IObservableMap
            var valObservableMap = val as IObservableMap <object, object>;

            if (valObservableMap != null)
            {
                var weakEvent = new WeakEventListener <IObservableMap <object, object>, object, IMapChangedEventArgs <object> >(valObservableMap)
                {
                    OnEventAction  = (instance, source, args) => obj.SetActive(IsNullOrEmpty(instance)),
                    OnDetachAction = (weakEventListener) => valObservableMap.MapChanged -= weakEventListener.OnEvent
                };

                valObservableMap.MapChanged += weakEvent.OnEvent;
            }
        }
Beispiel #26
0
 public NetworkConnectionStateTrigger()
 {
     WeakEventListener
     .AttachEvent <object>(
         handler => NetworkInformation.NetworkStatusChanged += new NetworkStatusChangedEventHandler(handler),
         handler => NetworkInformation.NetworkStatusChanged -= new NetworkStatusChangedEventHandler(handler),
         OnNetworkStatusChanged
         );
 }
Beispiel #27
0
        public SearchListView()
        {
            InitializeComponent();

            var dataContextChangedListener = 
                new WeakEventListener<SearchListView, SearchListView, DependencyPropertyChangedEventArgs>(this, this);
            DataContextChanged += dataContextChangedListener.OnEvent;
            dataContextChangedListener.OnEventAction = OnDataContextChanged;
            dataContextChangedListener.OnDetachAction = OnDetachDataContextChanged;
        }
 private void RegisterSelectedStopsSourceHandlers(ObservableCollection <TransitStop> collection)
 {
     if (SelectedStopsSource_CollectionChanged_Listener == null)
     {
         SelectedStopsSource_CollectionChanged_Listener = new WeakEventListener <StopDetailsPopupAddIn, object, NotifyCollectionChangedEventArgs>(this);
         SelectedStopsSource_CollectionChanged_Listener.OnEventAction  = (listener, sender, e) => listener.SelectedStopsSource_CollectionChanged(sender, e);
         SelectedStopsSource_CollectionChanged_Listener.OnDetachAction = (listener) => listener.OnEventAction = null;
         collection.CollectionChanged += SelectedStopsSource_CollectionChanged_Listener.OnEvent;
     }
 }
 private void RegisterStopsSourceHandlers(ObservableCollection <TransitStop> collection)
 {
     if (StopsSource_CollectionChanged_Listener == null)
     {
         StopsSource_CollectionChanged_Listener = new WeakEventListener <ShownStopsAddIn, object, NotifyCollectionChangedEventArgs>(this);
         StopsSource_CollectionChanged_Listener.OnEventAction  = (addin, sender, e) => addin.StopsSource_CollectionChanged(sender, e);
         StopsSource_CollectionChanged_Listener.OnDetachAction = (listener) => listener.OnEventAction = null;
         collection.CollectionChanged += StopsSource_CollectionChanged_Listener.OnEvent;
     }
 }
Beispiel #30
0
        protected override void OnAttached()
        {
            var _weakEventListener = new WeakEventListener <AnimatedNumberAction, object, EventArgs>(this);

            _weakEventListener.OnEventAction = (instance, source, eventArgs) =>
                                               instance.CompositionTarget_Rendering(source, eventArgs);
            _weakEventListener.OnDetachAction = (weakEventListener) =>
                                                CompositionTarget.Rendering -= weakEventListener.OnEvent;
            CompositionTarget.Rendering += _weakEventListener.OnEvent;
        }
Beispiel #31
0
 public VirtualizedTreeSource(CategoryScale scale, IHierarchyVirtualizationHelper virtualizer)
 {
     this._root        = (Category) new ShadowCategory();
     this._scale       = scale;
     this._virtualizer = virtualizer;
     this._leavesChangedWeakEventListener = new WeakEventListener <CategoryScale.VirtualizedTreeSource, object, EventArgs>(this);
     this._leavesChangedWeakEventListener.OnEventAction  = (Action <CategoryScale.VirtualizedTreeSource, object, EventArgs>)((instance, source, eventArgs) => instance.OnVirtualizerLeavesChanged(source, eventArgs));
     this._leavesChangedWeakEventListener.OnDetachAction = (Action <WeakEventListener <CategoryScale.VirtualizedTreeSource, object, EventArgs> >)(weakEventListener => this._virtualizer.LeavesChanged -= new EventHandler(weakEventListener.OnEvent));
     this._virtualizer.LeavesChanged += new EventHandler(this._leavesChangedWeakEventListener.OnEvent);
 }
 public WeakCollectionChangedWrapper( IList sourceList )
 {
     _innerList = sourceList;
       var notifyList = _innerList as INotifyCollectionChanged;
       if( notifyList != null )
       {
     _innerListListener = new WeakEventListener<NotifyCollectionChangedEventArgs>( OnInnerCollectionChanged );
     CollectionChangedEventManager.AddListener( notifyList, _innerListListener );
       }
 }
        public ResolveDatabaseObjectsViewModel()
        {
            DatabaseObjectList = new ObservableCollection<DatabaseObject>();

            var weakEventListener = new WeakEventListener<object, ObservableCollection<DatabaseObject>, EventArgs>(this, DatabaseObjectList);

            DatabaseObjectList.CollectionChanged += weakEventListener.OnEvent;
            weakEventListener.OnEventAction += RaiseChanges;

            weakEventListener.OnDetachAction += Static;
        }
Beispiel #34
0
            public void DoesNotLeakWithStaticEventHandlers()
            {
                var source = new EventSource();

                var weakEventListener = WeakEventListener <EventListener, EventSource, ViewModelClosedEventArgs> .SubscribeToWeakGenericEvent(null, source, "PublicEvent", EventListener.OnEventStaticHandler);

                Assert.IsTrue(weakEventListener.IsSourceAlive);
                Assert.IsFalse(weakEventListener.IsStaticEvent);
                Assert.IsFalse(weakEventListener.IsTargetAlive);
                Assert.IsTrue(weakEventListener.IsStaticEventHandler);
            }
Beispiel #35
0
 void SubscribeClickEvent(UIElement element)
 {
     if (element is FrontpageItemButton btn && !btn.ClickEventAttached)
     {
         WeakEventListener <Button, object, RoutedEventArgs> itemClickListener
             = new WeakEventListener <Button, object, RoutedEventArgs>(btn);
         itemClickListener.OnEventAction = (_, source, args) => ItemClicked?.Invoke(source, args);
         btn.Click += itemClickListener.OnEvent;
         btn.ClickEventAttached = true;
     }
 }
Beispiel #36
0
        public WeakCollectionChangedWrapper(IList sourceList)
        {
            _innerList = sourceList;
            var notifyList = _innerList as INotifyCollectionChanged;

            if (notifyList is not null)
            {
                _innerListListener = new WeakEventListener <NotifyCollectionChangedEventArgs>(OnInnerCollectionChanged);
                CollectionChangedEventManager.AddListener(notifyList, _innerListListener);
            }
        }
Beispiel #37
0
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            KeyboardLayoutVisualStateGroup = GetTemplateChild(VisualStateGroupKeyboardLayoutName) as VisualStateGroup;
            QuertyVisualState  = GetTemplateChild(VisualStateQuertyName) as VisualState;
            NumericVisualState = GetTemplateChild(VisualStateNumericName) as VisualState;

            foreach (var partName in TemplatePartNames.Keys)
            {
                var element = GetTemplateChild(partName) as Button;
                if (element != null)
                {
                    element.Command          = KeyStrokeCommand;
                    element.CommandParameter = TemplatePartNames[partName];
                    element.Content          = TemplatePartNames[partName].Name;

                    //element.TouchUp += new EventHandler<TouchEventArgs>(Button_TouchUp);
                    var touchUpEventListener = new WeakEventListener <QuertyKeyboard, object, TouchEventArgs>(this);
                    touchUpEventListener.OnEventAction  = (instance, source, eventArgs) => instance.OnButtonTouchUp(source, eventArgs);
                    touchUpEventListener.OnDetachAction = (weakEventListenerParameter) => element.TouchUp -= weakEventListenerParameter.OnEvent;
                    element.TouchUp += touchUpEventListener.OnEvent;

                    var touchDownEventListener = new WeakEventListener <QuertyKeyboard, object, TouchEventArgs>(this);
                    touchDownEventListener.OnEventAction  = (instance, source, eventArgs) => instance.OnButtonTouchDown(source, eventArgs);
                    touchDownEventListener.OnDetachAction = (weakEventListenerParameter) => element.TouchDown -= weakEventListenerParameter.OnEvent;
                    element.TouchDown += touchDownEventListener.OnEvent;

                    //element.Click += new RoutedEventHandler(Button_Click);
                    //var clickEventListener = new WeakEventListener<QuertyKeyboard, object, RoutedEventArgs>(this);
                    //clickEventListener.OnEventAction = (instance, source, eventArgs) => instance.OnButtonClicked(source, eventArgs);
                    //clickEventListener.OnDetachAction = (weakEventListenerParameter) => element.Click -= weakEventListenerParameter.OnEvent;
                    //element.Click += clickEventListener.OnEvent;

                    var mouseDownEventListener = new WeakEventListener <QuertyKeyboard, object, MouseButtonEventArgs>(this);
                    mouseDownEventListener.OnEventAction  = (instance, source, eventArgs) => instance.OnButtonMouseDown(source, eventArgs);
                    mouseDownEventListener.OnDetachAction = (weakEventListenerParameter) => element.MouseDown -= weakEventListenerParameter.OnEvent;
                    element.PreviewMouseDown += mouseDownEventListener.OnEvent;

                    var mouseUpEventListener = new WeakEventListener <QuertyKeyboard, object, MouseButtonEventArgs>(this);
                    mouseUpEventListener.OnEventAction  = (instance, source, eventArgs) => instance.OnButtonMouseUp(source, eventArgs);
                    mouseUpEventListener.OnDetachAction = (weakEventListenerParameter) => element.MouseUp -= weakEventListenerParameter.OnEvent;
                    element.PreviewMouseUp += mouseUpEventListener.OnEvent;
                }
#if DEBUG
                else
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("Part not found: {0}", partName));
                }
#endif
                OnShowCapitalize();
                //OnShiftPressed();
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="NetworkConnectionStateTrigger"/> class.
		/// </summary>
		public NetworkConnectionStateTrigger()
		{
			var weakEvent =
				new WeakEventListener<NetworkConnectionStateTrigger, object>(this)
				{
					OnEventAction = (instance, source) => NetworkInformation_NetworkStatusChanged(source),
					OnDetachAction = (instance, weakEventListener) => NetworkInformation.NetworkStatusChanged -= weakEventListener.OnEvent
				};
			NetworkInformation.NetworkStatusChanged += weakEvent.OnEvent;
			UpdateState();
		}
Beispiel #39
0
        public DiagramView()
        {
            InitializeComponent();
            KeyDown += DiagramPanel_KeyDown;

            var weakListener = new WeakEventListener<DiagramView, DiagramView, RoutedEventArgs>(this, this);

            this.Loaded += weakListener.OnEvent;
            weakListener.OnEventAction += OnDiagramViewLoaded;
            weakListener.OnDetachAction += Static;
        }
        public void HandleWeakEvent()
        {
            Dummy dummy = new Dummy();
            bool weakEventReceived = false;
            var listener = new WeakEventListener<PropertyChangedEventArgs>((sender, eventArgs) => weakEventReceived = true);

            PropertyChangedEventManager.AddListener(dummy, listener, String.Empty);
            dummy.RaisePropertyChanged();
            Assert.IsTrue(weakEventReceived);
            weakEventReceived = false;
        }
Beispiel #41
0
        public ScrollOnTouchAction()
        {
            //CompositionTarget.Rendering += new EventHandler(CompositionTarget_Rendering);
            var renderingEventListener = new WeakEventListener <ScrollOnTouchAction, object, EventArgs>(this);

            renderingEventListener.OnEventAction = (instance, source, eventArgs) =>
                                                   instance.CompositionTarget_Rendering(source, eventArgs);
            renderingEventListener.OnDetachAction = (weakEventListenerParameter) =>
                                                    CompositionTarget.Rendering -= weakEventListenerParameter.OnEvent;
            CompositionTarget.Rendering += renderingEventListener.OnEvent;
        }
        public void HandleWeakEvent()
        {
            Dummy dummy             = new Dummy();
            bool  weakEventReceived = false;
            var   listener          = new WeakEventListener <PropertyChangedEventArgs>((sender, eventArgs) => weakEventReceived = true);

            PropertyChangedEventManager.AddListener(dummy, listener, String.Empty);
            dummy.RaisePropertyChanged();
            Assert.IsTrue(weakEventReceived);
            weakEventReceived = false;
        }
Beispiel #43
0
 public MessageListener(InteractionMessenger messenger)
 {
     Dispatcher = Dispatcher.CurrentDispatcher;
     _source    = new WeakReference <InteractionMessenger>(messenger);
     _listener  = new WeakEventListener <EventHandler <InteractionMessageRaisedEventArgs>, InteractionMessageRaisedEventArgs>
                  (
         h => h,
         h => messenger.Raised += h,
         h => messenger.Raised -= h,
         MessageReceived
                  );
 }
Beispiel #44
0
        /// <summary>
        /// Initializes a new instance of the <see cref="TableDefinition" /> class.
        /// </summary>
        public TableDefinition()
        {
            FieldList = new List<TableFieldDefinition>();

            var relationships = new ObservableCollection<TableRelationshipDefinition>();
            Relationships = relationships;

            var weakListenerKeyDown = new WeakEventListener<TableDefinition, ObservableCollection<TableRelationshipDefinition>, NotifyCollectionChangedEventArgs>(this, relationships);
            relationships.CollectionChanged += weakListenerKeyDown.OnEvent;
            weakListenerKeyDown.OnEventAction += RelationshipsCollectionChanged;
            weakListenerKeyDown.OnDetachAction += Static;
        }
Beispiel #45
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceTypeInfo"/> class.
        /// </summary>
        /// <param name="type">The type.</param>
        public ServiceTypeInfo(ServiceExposedTypeEdit type)
        {
            _nameExpression = () => type.Name;
            _guidExpression = () => type.Guid;

            var propertyChangedListener =
                new WeakEventListener<ServiceTypeInfo, ServiceExposedTypeEdit, PropertyChangedEventArgs>(this, type);

            type.PropertyChanged += propertyChangedListener.OnEvent;
            propertyChangedListener.OnEventAction += OnTypePropertyChanged;
            propertyChangedListener.OnDetachAction += Static;
        }
        public void ShouldStoreEventHandler()
        {
            bool weakEventReceived = false;

            var listener = new WeakEventListener<PropertyChangedEventArgs>((sender, eventArgs) => weakEventReceived = true);

            // Check whether EventHandler was stored correctly.
            Assert.IsNotNull(listener.EventHandler);
            listener.EventHandler(null, null);
            Assert.IsTrue(weakEventReceived);
            weakEventReceived = false;
        }
Beispiel #47
0
        private static void OnDataContextChanged(SearchListView view, object sender, DependencyPropertyChangedEventArgs args)
        {
            var dc = args.NewValue as SearchListViewModel;
            if (dc == null)
                return;

            var selectedChangedListener = 
                new WeakEventListener<SearchListView, SearchListViewModel, SelectedChangedEventArgs>(view, dc);
            dc.SelectedChanged += selectedChangedListener.OnEvent;
            selectedChangedListener.OnEventAction = OnSelectedChanged;
            selectedChangedListener.OnDetachAction = OnDetachSelectedChanged;
        }
        public void ShouldStoreEventHandler()
        {
            bool weakEventReceived = false;

            var listener = new WeakEventListener <PropertyChangedEventArgs>((sender, eventArgs) => weakEventReceived = true);

            // Check whether EventHandler was stored correctly.
            Assert.IsNotNull(listener.EventHandler);
            listener.EventHandler(null, null);
            Assert.IsTrue(weakEventReceived);
            weakEventReceived = false;
        }
        /// <summary>
        /// Adds the event handlers.
        /// </summary>
        private void AddEventHandlers()
        {
            var propertyChangedListener = new WeakEventListener<BusinessObjectIsValidListener, BusinessBase, PropertyChangedEventArgs>(this, Model);
            Model.PropertyChanged += propertyChangedListener.OnEvent;
            propertyChangedListener.OnEventAction = OnModelPropertyChanged;
            propertyChangedListener.OnDetachAction = Static;

            var childChangedListener = new WeakEventListener<BusinessObjectIsValidListener, BusinessBase, ChildChangedEventArgs>(this, Model);
            Model.ChildChanged += childChangedListener.OnEvent;
            childChangedListener.OnEventAction = OnModelChildChanged;
            childChangedListener.OnDetachAction = Static;
        }
		private static void OnValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			var obj = (IsNullOrEmptyStateTrigger)d;
			var val = e.NewValue;

			obj.IsActive = IsNullOrEmpty(val);

			if (val == null)
				return;

			// Try to listen for various notification events
			// Starting with INorifyCollectionChanged
			var valNotifyCollection = val as INotifyCollectionChanged;
			if (valNotifyCollection != null)
			{
				var weakEvent = new WeakEventListener<INotifyCollectionChanged, object, NotifyCollectionChangedEventArgs>(valNotifyCollection)
				{
					OnEventAction = (instance, source, args) => obj.IsActive = IsNullOrEmpty(instance),
					OnDetachAction = (instance, weakEventListener) => instance.CollectionChanged -= weakEventListener.OnEvent
				};

				valNotifyCollection.CollectionChanged += weakEvent.OnEvent;
				return;
			}

			// Not INotifyCollectionChanged, try IObservableVector
			var valObservableVector = val as IObservableVector<object>;
			if (valObservableVector != null)
			{
				var weakEvent = new WeakEventListener<IObservableVector<object>, object, IVectorChangedEventArgs>(valObservableVector)
				{
					OnEventAction = (instance, source, args) => obj.IsActive = IsNullOrEmpty(instance),
					OnDetachAction = (instance, weakEventListener) => instance.VectorChanged -= weakEventListener.OnEvent
				};

				valObservableVector.VectorChanged += weakEvent.OnEvent;
				return;
			}

			// Not INotifyCollectionChanged, try IObservableMap
			var valObservableMap = val as IObservableMap<object,object>;
			if (valObservableMap != null)
			{
				var weakEvent = new WeakEventListener<IObservableMap<object, object>, object, IMapChangedEventArgs<object>>(valObservableMap)
				{
					OnEventAction = (instance, source, args) => obj.IsActive = IsNullOrEmpty(instance),
					OnDetachAction = (instance, weakEventListener) => instance.MapChanged -= weakEventListener.OnEvent
				};

				valObservableMap.MapChanged += weakEvent.OnEvent;
			}
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="AdaptiveTrigger"/> class.
 /// </summary>
 public AdaptiveTrigger()
 {
   var window = CoreApplication.GetCurrentView()?.CoreWindow;
   if (window != null)
   {
     var weakEvent = new WeakEventListener<AdaptiveTrigger, CoreWindow, WindowSizeChangedEventArgs>(this)
     {
       OnEventAction = (instance, s, e) => OnCoreWindowOnSizeChanged(s, e),
       OnDetachAction = (instance, weakEventListener) => window.SizeChanged -= weakEventListener.OnEvent
     };
     window.SizeChanged += weakEvent.OnEvent;
   }
 }
        public MasterDetailStateTrigger()
        {
            if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
            {
                var weakEvent = new WeakEventListener<MasterDetailStateTrigger, ApplicationView, object>(this)
                {
                    OnEventAction = (instance, source, eventArgs) => MasterDetailStatetateTrigger_MasterDetailStateChanged(source, eventArgs),
                    OnDetachAction = (instance, weakEventListener) => ApplicationView.GetForCurrentView().VisibleBoundsChanged -= weakEventListener.OnEvent
                };

                ApplicationView.GetForCurrentView().VisibleBoundsChanged += weakEvent.OnEvent;
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="OrientationStateTrigger"/> class.
		/// </summary>
		public OrientationStateTrigger()
		{
			if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
			{
				var weakEvent =
					new WeakEventListener<OrientationStateTrigger, DisplayInformation, object>(this)
					{
						OnEventAction = (instance, source, eventArgs) => OrientationStateTrigger_OrientationChanged(source, eventArgs),
						OnDetachAction = (instance, weakEventListener) => DisplayInformation.GetForCurrentView().OrientationChanged -= weakEventListener.OnEvent
					};
				DisplayInformation.GetForCurrentView().OrientationChanged += weakEvent.OnEvent;
			}
		}
        public DocumentationStepView()
        {
            InitializeComponent();

            var contextMenu = new ContextMenu();
            var contextMenuShowingListener = new WeakEventListener<DocumentationStepView, ContextMenu, ContextMenuEventArgs>(this, contextMenu);
            contextMenu.Showing += contextMenuShowingListener.OnEvent;
            contextMenuShowingListener.OnEventAction += ContextMenu_Showing;
            contextMenuShowingListener.OnDetachAction += Static;

            HTMLRichTextBox.ContextMenu = contextMenu;
            Loaded += DocumentationStepView_Loaded;
            Unloaded += OnUnloaded;
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="UserInteractionModeTrigger"/> class.
 /// </summary>
 public UserInteractionModeTrigger()
 {
     if (!Windows.ApplicationModel.DesignMode.DesignModeEnabled)
     {
         var weakEvent =
             new WeakEventListener<UserInteractionModeTrigger, object, WindowSizeChangedEventArgs>(this)
             {
                 OnEventAction = (instance, source, eventArgs) => UserInteractionModeTrigger_SizeChanged(source, eventArgs),
                 OnDetachAction = (instance, weakEventListener) => Window.Current.SizeChanged -= weakEventListener.OnEvent
             };
         Window.Current.SizeChanged += weakEvent.OnEvent;
         UpdateTrigger(InteractionMode);
     }
 }
 public StopPopupControl()
 {
     this.InitializeComponent();
     MainGrid.DataContext = VM;
     VM.PropertyChanged += VM_PropertyChanged;
     RefreshMainGridWidth();
     //ExpandButton.SetBinding(Button.CommandProperty, new Binding() { Source = this, Path = new PropertyPath("ExpandCommand") });
     //CompressButton.SetBinding(Button.CommandProperty, new Binding() { Source = this, Path = new PropertyPath("CompressCommand") });
     //CloseButton.SetBinding(Button.CommandProperty, new Binding() { Source = this, Path = new PropertyPath("CloseCommand") });
     //RegisterPropertyChangedCallback(WidthProperty, WidthChanged);
     ShownArrivalsBinding = new CompositeCollectionBinding<RealTimeArrival, string>(ShownArrivals);
     WeakEventListener<StopPopupControl, object, NotifyCollectionChangedEventArgs> childrenListener = new WeakEventListener<StopPopupControl, object, NotifyCollectionChangedEventArgs>(this);
     childrenListener.OnEventAction = (t, s, e) => t.Children_CollectionChanged(s, e);
     VM.Children.CollectionChanged += childrenListener.OnEvent;
 }
        public void AllowsGarbageCollection()
        {
            Dummy dummy = new Dummy();
            bool weakEventReceived = false;
            var listener = new WeakEventListener<PropertyChangedEventArgs>((sender, eventArgs) => weakEventReceived = true);

            PropertyChangedEventManager.AddListener(dummy, listener, String.Empty);

            WeakReference weakReference = new WeakReference(listener);
            listener = null;
            GC.Collect();

            Assert.IsFalse(weakReference.IsAlive);
            Assert.IsFalse(weakEventReceived);
        }
        private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs args)
        {
            var newDc = args.NewValue as IFieldViewModel;
            if (newDc == null)
                return;

            DetachDisposedListener();

            _disposedListener = new WeakEventListener<DynamicItemsSelectorView, IFieldViewModel, EventArgs>(this, newDc)
                                    {
                                        OnEventAction = OnDataContextDisposed,
                                        OnDetachAction = OnDetachDataContextDisposed
                                    };
            newDc.Disposed += _disposedListener.OnEvent;
        }
        /// <summary>
		/// Initializes a new instance of the <see cref="AdaptiveTrigger"/> class.
		/// </summary>
        public AdaptiveTrigger()
        {
            this.RegisterPropertyChangedCallback(MinWindowHeightProperty, OnMinWindowHeightPropertyChanged);
            this.RegisterPropertyChangedCallback(MinWindowWidthProperty, OnMinWindowWidthPropertyChanged);
            
            var window = CoreApplication.GetCurrentView()?.CoreWindow;
            if (window != null)
            {
                var weakEvent = new WeakEventListener<AdaptiveTrigger, CoreWindow, WindowSizeChangedEventArgs>(this)
                {
                    OnEventAction = (instance, s, e) => OnCoreWindowOnSizeChanged(s, e),
                    OnDetachAction = (instance, weakEventListener) => window.SizeChanged -= weakEventListener.OnEvent
                };
                window.SizeChanged += weakEvent.OnEvent;
            }
        }
        /// <summary>
        /// Initializes the specified model.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="processEdit">The process edit.</param>
        /// <param name="fieldEdit">The field edit.</param>
        public void Init(ChecklistSettingsStepEdit model, ProcessEdit processEdit, FieldEdit fieldEdit)
        {
            StepModel = model;
            ProcessEdit = processEdit;
            FieldEdit = fieldEdit;

            FilterGuid = model.FilterGuid ?? Guid.Empty;
            FilterDefinition = model.FilterDefinition;

            var weakListener = new WeakEventListener<ChecklistFilterViewModel, ChecklistSettingsStepEdit, PropertyChangedEventArgs>(this, model);

            model.PropertyChanged += weakListener.OnEvent;
            weakListener.OnEventAction += OnReqStepPropertyChanged;
            weakListener.OnDetachAction += Static;

            LoadProcessInfo(model);
        }