public void Handler_Invoke_CallsTarget() { var target = new Stub1(); var handler = new WeakEventHandler<Stub1, EventArgs>(target.Handler, eh => { }).HandlerT; handler(this, new EventArgs()); Assert.AreEqual(1, target.FireCount); }
public ToolStripMenuItem AddToolStripMenuItem(string text, Bitmap bitmap, EventHandler<EventArgs> clickEvent, Keys keys, Func<bool> enabled) { var menuItem = new ToolStripMenuItem(text); if (bitmap != null) { menuItem.Image = bitmap; } if (keys != Keys.None) { menuItem.ShortcutKeys = keys; } if (clickEvent != null) { menuItem.Click += new WeakEventHandler<EventArgs>(clickEvent).Handler; } Items.Add(menuItem); EventHandler<EventArgs> toolstripOpening = (sender, args) => { menuItem.Enabled = enabled(); }; Opening += new WeakEventHandler<EventArgs>(toolstripOpening).Handler; return menuItem; }
public void IsHandlerFor_Null_Throws() { var target = new Stub1(); var handler = new WeakEventHandler<Stub1, EventArgs>(target.Handler, eh => { }); Assert.IsFalse(handler.IsHandlerFor(null)); }
public void IsHandlerFor_TargetGC_False() { var target = new Stub1(); var handler = new WeakEventHandler<Stub1, EventArgs>(target.Handler, eh => { }); target = null; System.GC.Collect(); Assert.IsFalse(handler.IsHandlerFor(new Stub1().Handler)); }
internal TextTracker( Workspace workspace, DocumentId documentId, SourceTextContainer textContainer, Action <Workspace, DocumentId, SourceText, PreservationMode> onChangedHandler) { this.workspace = workspace; this.documentId = documentId; this.TextContainer = textContainer; this.onChangedHandler = onChangedHandler; // use weak event so TextContainer cannot accidently keep workspace alive. this.weakOnTextChanged = WeakEventHandler <TextChangeEventArgs> .Create(this, (target, sender, args) => target.OnTextChanged(sender, args)); }
protected WeakEventSubscription(TEventSource eventSource, EventHandler <TEventArgs> eventHandler) { if (eventSource == null) { throw new ArgumentNullException(nameof(eventSource)); } if (eventHandler == null) { throw new ArgumentNullException(nameof(eventHandler)); } _eventSourceWeakReference = new WeakReference <TEventSource>(eventSource); _weakEventHandler = new WeakEventHandler <TEventArgs>(eventHandler); }
/// <summary> /// Removes the event handlers for the watch /// </summary> protected void ClearWatch() { if (null != _weakDocNodeTunneledEventHandler) { _weakDocNodeTunneledEventHandler.Remove(); _weakDocNodeTunneledEventHandler = null; } if (null != _weakDocNodeChangedHandler) { _weakDocNodeChangedHandler.Remove(); _weakDocNodeChangedHandler = null; } }
public void HandleEvent() { var listener = new ListenerWithEventArgs(); WeakEventHandler <EventArgs> .Register( this, listener, (s, h) => s.Event += h, (s, h) => s.Event -= h, (l, s, e) => l.OnEvent(s, e)); RaiseEvent(); Assert.IsTrue(listener.EventReceived); }
public void DetachEventHandler() { var listener = new ListenerWithEventArgs(); var subscription = WeakEventHandler <EventArgs> .Register( this, listener, (s, h) => s.Event += h, (s, h) => s.Event -= h, (l, s, e) => l.OnEvent(s, e)); subscription.Dispose(); RaiseEvent(); Assert.IsFalse(listener.EventReceived); }
public void Handler_Invoke_TargetGC_CallsUnregister() { bool unregister = false; var target = new Stub1(); var handler = new WeakEventHandler<Stub1, EventArgs>(target.Handler, eh => { unregister = true; }).HandlerT; handler(this, new EventArgs()); Assert.AreEqual(1, target.FireCount); target = null; System.GC.Collect(); handler(this, new EventArgs()); Assert.IsTrue(unregister); }
public void TestUnsubscription_Simple() { EventRaisingClass observed = new EventRaisingClass(); _eventRaised = false; var handler = new WeakEventHandler <EventArgs>(GetCallback(), h => observed.Event -= h); observed.Event += handler.Handler; Assert.AreEqual(1, observed.SubscriptionCount); // unregistration should detach event observed.Event -= handler.Handler; Assert.AreEqual(0, observed.SubscriptionCount); Assert.IsFalse(_eventRaised); }
public void Handler_Invoke_TargetGC_CallsUnregister() { bool unregister = false; var target = new Stub1(); var handler = new WeakEventHandler <Stub1, EventArgs>(target.Handler, eh => { unregister = true; }).HandlerT; handler(this, new EventArgs()); Assert.AreEqual(1, target.FireCount); target = null; System.GC.Collect(); handler(this, new EventArgs()); Assert.IsTrue(unregister); }
public void HandleEvent() { var listener = new PropertyChangedListener(); WeakEventHandler <PropertyChangedEventHandler, PropertyChangedEventArgs> .Register( this, listener, handler => new PropertyChangedEventHandler(handler), (s, h) => s.PropertyChanged += h, (s, h) => s.PropertyChanged -= h, (l, s, e) => l.OnEvent(s, e)); RaiseEvent(); Assert.IsTrue(listener.EventReceived); }
public void DetachEventHandler() { var listener = new PropertyChangedListener(); var subscription = WeakEventHandler <PropertyChangedEventHandler, PropertyChangedEventArgs> .Register( this, listener, handler => new PropertyChangedEventHandler(handler), (s, h) => s.PropertyChanged += h, (s, h) => s.PropertyChanged -= h, (l, s, e) => l.OnEvent(s, e)); subscription.Dispose(); RaiseEvent(); Assert.IsFalse(listener.EventReceived); }
private void DetachData(IEnumerable data) { if (this.collectionChangedHandler != null) { this.collectionChangedHandler.Unsubscribe(); this.collectionChangedHandler = null; } if (this.currentChangedHandler != null) { this.currentChangedHandler.Unsubscribe(); this.currentChangedHandler = null; } this.DetachDataOverride(); }
/// <summary> /// Binds the specified data source. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="propertyName">Name of the property.</param> public void Bind(object dataSource, string propertyName) { Check.ArgumentNotNull(dataSource, nameof(dataSource)); Check.ArgumentNotEmpty(propertyName, nameof(propertyName)); try { _isBinding = true; if (_boundObject != null) { var i = _boundObject as INotifyPropertyChanged; if (i != null) { i.PropertyChanged -= OnBoundObjectPropertyChanged; } } _boundObject = dataSource; _boundObjectType = _boundObject.GetType(); _boundProperty = _boundObjectType.GetProperty(propertyName); if (_boundProperty == null) { throw new InvalidOperationException("Could not find property " + _boundProperty + " of databound object (" + _boundObjectType.Name + ")"); //LOCALIZEME } //Set initial value var val = _boundProperty.GetValue(_boundObject, null); if (val != null) { this.Content = val.ToString(); } else { this.Content = null; } var inp = _boundObject as INotifyPropertyChanged; if (inp != null) { inp.PropertyChanged += WeakEventHandler.Wrap <PropertyChangedEventHandler>(OnBoundObjectPropertyChanged, (eh) => inp.PropertyChanged -= eh); } } finally { _isBinding = false; } }
/// <summary> /// Removes the event handlers for the watch /// </summary> protected void ClearWatch() { #if DEBUG_DOCNODEPROXYLOGGING Current.Console.WriteLine("DocNodeProxy.ClearWatch: path={0}", _docNodePath.ToString()); #endif if (null != _weakDocNodeTunneledEventHandler) { _weakDocNodeTunneledEventHandler.Remove(); _weakDocNodeTunneledEventHandler = null; } if (null != _weakDocNodeChangedHandler) { _weakDocNodeChangedHandler.Remove(); _weakDocNodeChangedHandler = null; } }
public static TResult CreateWeakDelegate <TTarget, TArg, TResult>([NotNull] TTarget target, [NotNull] Action <TTarget, object, TArg> invokeAction, [CanBeNull] Action <object, TResult> unsubscribeAction, [NotNull] Func <IWeakEventHandler <TArg>, TResult> createHandler) where TTarget : class where TResult : class { Should.NotBeNull(createHandler, nameof(createHandler)); var weakEventHandler = new WeakEventHandler <TTarget, TArg, TResult>(target, invokeAction, unsubscribeAction); var handler = createHandler(weakEventHandler); if (unsubscribeAction == null) { return(handler); } weakEventHandler.HandlerDelegate = handler; return(handler); }
public override void Bind(IEditorService service) { _edsvc = service; _edsvc.RegisterCustomNotifier(this); var res = service.GetEditedResource() as ILayerDefinition; Debug.Assert(res != null); _rl = res.SubLayer as IRasterLayerDefinition; Debug.Assert(_rl != null); TextBoxBinder.BindText(txtFeatureSource, _rl, nameof(_rl.ResourceId)); TextBoxBinder.BindText(txtFeatureClass, _rl, nameof(_rl.FeatureName)); TextBoxBinder.BindText(txtGeometry, _rl, nameof(_rl.Geometry)); _rl.PropertyChanged += WeakEventHandler.Wrap <PropertyChangedEventHandler>(OnRasterLayerPropertyChanged, (eh) => _rl.PropertyChanged -= eh); }
public void FirePropertyChangedEvent_Always_CallsCallback() { EventListenerStub listener = new EventListenerStub(); Person person = new Person(); WeakEventHandler weakEventHandler = WeakPropertyChangedEventHandler.Register( person, (s, eh) => s.PropertyChanged -= eh, listener, (me, sender, ea) => me.OnPropertyChanged(sender, ea)); person.Name = "Bob"; Assert.AreEqual(1, listener.EventHandlerCallCount); Assert.AreEqual("Name", listener.LastPropertyChanged); }
public ExtendedClassSettings(IFeatureSource fs, IEnumerable <string> qualifiedClassNames, IFeatureSourceExtension ext) : this() { _fs = fs; _ext = ext; var names = new List <string>(qualifiedClassNames); cmbBaseClass.DataSource = names; ext.PropertyChanged += WeakEventHandler.Wrap <PropertyChangedEventHandler>(OnExtensionPropertyChanged, (eh) => ext.PropertyChanged -= eh); //HACK if (string.IsNullOrEmpty(_ext.FeatureClass)) { _ext.FeatureClass = names[0]; } ComboBoxBinder.BindSelectedIndexChanged(cmbBaseClass, nameof(cmbBaseClass.SelectedItem), ext, nameof(ext.FeatureClass)); }
public GroupPropertiesCtrl(ITileSetDefinition map, IBaseMapGroup group) : this() { _init = true; try { _mdf = map; _el = group; group.PropertyChanged += WeakEventHandler.Wrap <PropertyChangedEventHandler>(OnGroupChanged, (eh) => group.PropertyChanged -= eh); txtName.Text = group.Name; TextBoxBinder.BindText(txtLegendLabel, group, nameof(group.LegendLabel)); } finally { _init = false; } }
private void AddMap(IMapGroup group) { var item = new ListViewItem(); item.ImageIndex = 0; item.Text = item.Name = group.id; item.Tag = group; PropertyChangedEventHandler groupChange = (s, e) => { if (e.PropertyName == nameof(group.id)) { item.Text = group.id; } }; group.PropertyChanged += WeakEventHandler.Wrap(groupChange, (eh) => group.PropertyChanged -= eh); lstMaps.Items.Add(item); }
public override void Bind(IEditorService service) { service.RegisterCustomNotifier(this); _service = service; _loadProc = _service.GetEditedResource() as ILoadProcedure; _fProc = _loadProc.SubType; TextBoxBinder.BindText(txtTargetRoot, _fProc, "RootPath"); CheckBoxBinder.BindChecked(chkCreateFeatureSources, _fProc, "GenerateSpatialDataSources"); CheckBoxBinder.BindChecked(chkCreateLayers, _fProc, "GenerateLayers"); TextBoxBinder.BindText(txtFeatureSourceRoot, _fProc, "SpatialDataSourcesPath"); TextBoxBinder.BindText(txtFeatureFolderName, _fProc, "SpatialDataSourcesFolder"); TextBoxBinder.BindText(txtLayerRoot, _fProc, "LayersPath"); TextBoxBinder.BindText(txtLayerFolderName, _fProc, "LayersFolder"); _fProc.PropertyChanged += WeakEventHandler.Wrap <PropertyChangedEventHandler>(OnLoadProcedurePropertyChanged, (eh) => _fProc.PropertyChanged -= eh); }
public void Register_ListenerSetToNullAndGarbageCollected_ListenerSetToNull() { EventListenerStub listener = new EventListenerStub(); WeakReference listenerRef = new WeakReference(listener); Person person = new Person(); WeakEventHandler weakEventHandler = WeakPropertyChangedEventHandler.Register( person, (s, eh) => s.PropertyChanged -= eh, listener, (me, sender, ea) => me.OnPropertyChanged(sender, ea)); listener = null; GC.Collect(); Assert.IsFalse(listenerRef.IsAlive); }
private IndexingSkipList <IList <TResult> > .Node RecordItem(IndexingSkipList <IList <TResult> > .Node nodeBefore, TSource item, IList <TResult> collection) { int count = GetCount(collection); var newNode = _collectionIndex.AddAfter(nodeBefore, count, collection); RecordNodeForItemInLookupTables(item, collection, newNode); if (collection != null && !_weakEventHandlers.ContainsKey(collection)) { WeakEventHandler weakEventHandler = WeakNotifyCollectionChangedEventHandler.Register( (INotifyCollectionChanged)collection, this, (me, sender, args) => me.OnSubCollectionChanged(sender, args)); _weakEventHandlers.Add(collection, weakEventHandler); } return(newNode); }
internal void Bind(ISearchCommand searchCommandType, IEditorService service) { cmbTargetFrame.DataSource = Enum.GetValues(typeof(TargetType)); _init = true; Bind(service); _cmd = searchCommandType; _wl = (IWebLayout)_edsvc.GetEditedResource(); var wlMap = _wl.Map; wlMap.PropertyChanged += WeakEventHandler.Wrap <PropertyChangedEventHandler>(OnWebMapLayoutPropertyChanged, (eh) => wlMap.PropertyChanged -= eh); LoadLayers(); if (!string.IsNullOrEmpty(_cmd.Layer)) { foreach (var lyr in _layers) { if (lyr.Name == _cmd.Layer) { txtLayer.Text = _cmd.Layer; txtLayer.Tag = lyr.ResourceId; } } } TextBoxBinder.BindText(txtFrame, _cmd, nameof(_cmd.TargetFrame)); ComboBoxBinder.BindSelectedIndexChanged(cmbTargetFrame, nameof(cmbTargetFrame.SelectedItem), _cmd, nameof(_cmd.Target)); TextBoxBinder.BindText(txtLayer, _cmd, nameof(_cmd.Layer)); TextBoxBinder.BindText(txtFilter, _cmd, nameof(_cmd.Filter)); TextBoxBinder.BindText(txtPrompt, _cmd, nameof(_cmd.Prompt)); NumericBinder.BindValueChanged(numLimit, _cmd, nameof(_cmd.MatchLimit)); UpdateColumns(); foreach (var col in _cmd.ResultColumns.Column) { _columns.Add(col); } grdOutputColumns.DataSource = _columns; _columns.AddingNew += OnAddingNewColumn; _columns.ListChanged += OnColumnsChanged; }
private void btnNewCalculation_Click(object sender, EventArgs e) { if (_edSvc.IsNew) { MessageBox.Show(Strings.SaveResourceFirst); return; } var node = trvExtensions.SelectedNode; if (node != null) { var ext = node.Tag as IFeatureSourceExtension; if (ext != null) { var calc = ObjectFactory.CreateCalculatedProperty(); var cNode = new TreeNode(); cNode.ImageIndex = cNode.SelectedImageIndex = IDX_CALC; cNode.Tag = calc; PropertyChangedEventHandler calcChange = (s, evt) => { if (evt.PropertyName == nameof(calc.Name)) { cNode.Text = calc.Name; } else if (evt.PropertyName == nameof(calc.Expression)) { cNode.ToolTipText = calc.Expression; } }; calc.PropertyChanged += WeakEventHandler.Wrap(calcChange, (eh) => calc.PropertyChanged -= eh); node.Nodes.Add(cNode); node.Expand(); ext.AddCalculatedProperty(calc); OnResourceChanged(); trvExtensions.SelectedNode = cNode; } } }
public void WhenDetached_ThenDoesNotInvokeCallbackOnEvent() { var instance = this; var sender = new EventSource(); var invoked = false; var weakHandler = new WeakEventHandler <WeakEventListenerFixture, object, EventArgs>( instance, (i, s, e) => { invoked = true; }, handler => { sender.Event -= handler.OnEvent; }); sender.Event += weakHandler.OnEvent; weakHandler.Detach(); sender.FireEvent(new EventArgs()); Assert.IsFalse(invoked); }
public void WhenDetached_ThenDoesNotInvokeCallbackOnEvent() { var instance = this; var sender = new EventSource(); var invoked = false; var weakHandler = new WeakEventHandler<WeakEventListenerFixture, object, EventArgs>( instance, (i, s, e) => { invoked = true; }, handler => { sender.Event -= handler.OnEvent; }); sender.Event += weakHandler.OnEvent; weakHandler.Detach(); sender.FireEvent(new EventArgs()); Assert.IsFalse(invoked); }
public void WhenDetachedWithNullDetachAction_ThenInvokesCallbackOnEvent() { var instance = this; var sender = new EventSource(); var invoked = false; var weakHandler = new WeakEventHandler <WeakEventListenerFixture, object, EventArgs>( instance, (i, s, e) => { invoked = true; }, null); sender.Event += weakHandler.OnEvent; weakHandler.Detach(); sender.FireEvent(new EventArgs()); Assert.IsTrue(invoked); }
public void TestWeakEvent_Complex() { EventRaisingClass observed = new EventRaisingClass(); _eventRaised = false; var weakEventHandler = new WeakEventHandler <EventHandler <EventArgs>, EventArgs>(GetCallback(), h => observed.Event -= h); observed.Event += weakEventHandler.Handler; Assert.AreEqual(1, observed.SubscriptionCount); // when target goes out of scope, event is not detached. the observer will be // temporarily leaked until the event fires InvalidateEventHandler(weakEventHandler); Assert.AreEqual(1, observed.SubscriptionCount); // if the target is no longer alive when the event is raised, the event handler should be // automatically unregistered, which will cause the observer to unsubscribe from the source observed.RaiseEvent(EventArgs.Empty); Assert.AreEqual(0, observed.SubscriptionCount); Assert.IsFalse(_eventRaised); }
private void ChangeItemsSource(object newValue) { if (this.collectionChangedEventHandler != null) { this.collectionChangedEventHandler.Unsubscribe(); this.collectionChangedEventHandler = null; } this.itemsSourceCache = newValue as IEnumerable; if (this.itemsSourceCache is INotifyCollectionChanged) { this.collectionChangedEventHandler = new WeakEventHandler <NotifyCollectionChangedEventArgs>(this.itemsSourceCache, this, KnownEvents.CollectionChanged); } // TODO: Hook property changed for each item if (this.IsTemplateApplied) { this.InvalidateUI(); this.ScheduleUpdate(); } }
private void AttachSourceEvents() { if (this.sourceAsEnumerable == null) { return; } INotifyCollectionChanged collectionChanged = this.sourceAsEnumerable as INotifyCollectionChanged; if (collectionChanged != null) { this.collectionChangedHandler = new WeakEventHandler <NotifyCollectionChangedEventArgs>(collectionChanged, this, KnownEvents.CollectionChanged); } ICollectionView collectionView = this.sourceAsEnumerable as ICollectionView; if (collectionView != null) { this.vectorChangedHandler = new WeakEventHandler <IVectorChangedEventArgs>(collectionView, this, KnownEvents.VectorChanged); } }
private void OnPieChartChanged(DependencyObject source) { // Unsubscribe from previous collection. if (_pieChartSubscription != null) { _pieChartSubscription.Dispose(); _pieChartSubscription = null; } // Get pie chart from source. if (source != null) { _pieChart = source.GetVisualSubtree().OfType <PieChart>().FirstOrDefault(); } if (_pieChart != null) { // Bind legend title to pie chart title. SetBinding(TitleProperty, new Binding("Title") { Source = _pieChart }); // Subscribe to changes in pie chart using weak event pattern. _pieChartSubscription = WeakEventHandler <EventArgs> .Register( _pieChart, this, (sender, handler) => sender.Updated += handler, (sender, handler) => sender.Updated -= handler, (listener, sender, eventArgs) => listener.Update()); } else { // Reset legend title. ClearValue(TitleProperty); } Update(); }
//-------------------------------------------------------------- #region Creation & Cleanup //-------------------------------------------------------------- /// <summary> /// Initializes a new instance of the <see cref="ObservablePointListWrapper"/> class. /// </summary> /// <param name="list">The list of points that should be wrapped.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="list"/> is <see langword="null"/>. /// </exception> public ObservablePointListWrapper(IList <Point> list) { if (list == null) { throw new ArgumentNullException("list"); } _list = list; var observableCollection = list as INotifyCollectionChanged; if (observableCollection != null) { WeakEventHandler <NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs> .Register( observableCollection, this, handler => new NotifyCollectionChangedEventHandler(handler), (sender, handler) => sender.CollectionChanged += handler, (sender, handler) => sender.CollectionChanged -= handler, (listener, sender, eventArgs) => listener.OnCollectionChanged(sender, eventArgs)); } }
public void WhenAttachedToAnEvent_ThenInvokesCallbackOnEvent() { var instance = this; var sender = new EventSource(); var args = new EventArgs(); var invoked = false; var weakHandler = new WeakEventHandler<WeakEventListenerFixture, object, EventArgs>( instance, (i, s, e) => { Assert.AreSame(this, i); Assert.AreSame(sender, s); Assert.AreSame(args, e); invoked = true; }, handler => { sender.Event -= handler.OnEvent; }); sender.Event += weakHandler.OnEvent; sender.FireEvent(args); Assert.IsTrue(invoked); }
public void WhenInstanceIsNull_ThenHandlerIsDetached() { WeakEventListenerFixture instance = null; var sender = new EventSource(); var invoked = false; var detached = false; var weakHandler = new WeakEventHandler<WeakEventListenerFixture, object, EventArgs>( instance, (i, s, e) => { invoked = true; }, handler => { sender.Event -= handler.OnEvent; detached = true; }); sender.Event += weakHandler.OnEvent; sender.FireEvent(new EventArgs()); Assert.IsFalse(invoked); Assert.IsTrue(detached); }
public void IsHandlerFor_CorrectHandler_True() { var target = new Stub1(); var handler = new WeakEventHandler<Stub1, EventArgs>(target.Handler, eh => { }); Assert.IsTrue(handler.IsHandlerFor(target.Handler)); }
/// <summary> /// Sets the document node that is held by this proxy. /// </summary> /// <param name="value">The document node. If <c>docNode</c> implements <see cref="Main.IDocumentLeafNode" />, /// the document path is stored for this object in addition to the object itself.</param> /// <param name="parentNode">The start point of the document path. Should be equal to the member _parent, but this might be not set now.</param> protected void InternalSetDocNode(Main.IDocumentLeafNode value, IDocumentLeafNode parentNode) { if (!IsValidDocument(value)) throw new ArgumentException("This type of document is not allowed for the proxy of type " + this.GetType().ToString()); if (null == parentNode) throw new InvalidOperationException("Parent of this node must be set in order to set the docnode."); var oldValue = this.InternalDocNode; if (object.ReferenceEquals(oldValue, value)) return; // Nothing to do if (null != _weakDocNodeChangedHandler) { _weakDocNodeChangedHandler.Remove(); _weakDocNodeChangedHandler = null; } if (null != _weakDocNodeTunneledEventHandler) { _weakDocNodeTunneledEventHandler.Remove(); _weakDocNodeTunneledEventHandler = null; } if (null != oldValue) { ClearDocNode(); } var newPath = RelativeDocumentPath.GetRelativePathFromTo(parentNode, value); if (null != newPath) InternalDocumentPath = newPath; // especially in dispose situations, the new path can be null. In this case we leave the path as it was _docNodeRef = new WeakReference(value); #if DEBUG_DOCNODEPROXYLOGGING Current.Console.WriteLine("RelDocNodeProxy.SetDocNode, path is <<{0}>>", _docNodePath); #endif value.TunneledEvent += (_weakDocNodeTunneledEventHandler = new WeakActionHandler<object, object, TunnelingEventArgs>(EhDocNode_TunneledEvent, handler => value.TunneledEvent -= handler)); if (null != _docNodePath && !_docNodePath.IsIdentity) // it does not make sense to watch the changed event of our target node is our parent because the parent can handle the Changed event itself { value.Changed += (_weakDocNodeChangedHandler = new WeakEventHandler(EhDocNode_Changed, handler => value.Changed -= handler)); } OnAfterSetDocNode(); EhSelfChanged(new Main.InstanceChangedEventArgs(oldValue, value)); }
private void InternalInitializeGraphDocument(GraphDocument doc) { if (_doc != null) throw new ApplicationException(nameof(_doc) + " is already initialized"); if (doc == null) throw new ArgumentNullException(nameof(doc)); _doc = doc; { // we are using weak events here, to avoid that _doc will maintain strong references to the controller // Attention: use local variable doc instead of member _doc for the anonymous methods below! var rootLayer = doc.RootLayer; // local variable for rootLayer _weakEventHandlersForDoc = new WeakEventHandler[3]; // storage for WeakEventhandlers for later removal doc.Changed += (_weakEventHandlersForDoc[0] = new WeakEventHandler(this.EhGraph_Changed, x => doc.Changed -= x)); rootLayer.LayerCollectionChanged += (_weakEventHandlersForDoc[1] = new WeakEventHandler(this.EhGraph_LayerCollectionChanged, x => rootLayer.LayerCollectionChanged -= x)); doc.SizeChanged += (_weakEventHandlersForDoc[2] = new WeakEventHandler(this.EhGraph_SizeChanged, x => doc.SizeChanged -= x)); } // if the host layer has at least one child, we set the active layer to the first child of the host layer if (_doc.RootLayer.Layers.Count >= 1) _currentLayerNumber = new List<int>() { 0 }; // Ensure the current layer and plot numbers are valid this.EnsureValidityOfCurrentLayerNumber(); this.EnsureValidityOfCurrentPlotNumber(); OnTitleNameChanged(EventArgs.Empty); }
private void ProcessDelayedItemsSourceChanged() { if( this.ShouldSynchronizeCurrentItem ) { DataGridContext localContext = this.DataGridContext; object currentItem = this.Items.CurrentItem; int currentItemIndex = this.Items.CurrentPosition; if( ( this.Items.IsCurrentAfterLast ) || ( this.Items.IsCurrentBeforeFirst ) ) { currentItemIndex = -1; } localContext.SetCurrent( currentItem, null, currentItemIndex, null, false, false, this.SynchronizeSelectionWithCurrent ); if( !this.SynchronizeSelectionWithCurrent ) { m_selectionChangerManager.Begin(); try { if( ( this.SelectionUnit == SelectionUnit.Row ) && ( !this.Items.IsCurrentAfterLast ) && ( !this.Items.IsCurrentBeforeFirst ) && ( currentItemIndex != -1 ) ) { m_selectionChangerManager.SelectJustThisItem( localContext, currentItemIndex, currentItem ); } else { m_selectionChangerManager.UnselectAll(); } } finally { m_selectionChangerManager.End( true, false, false ); } } } this.DataGridContext.ItemsSourceFieldDescriptors = null; ItemsSourceHelper.CleanUpColumns( this.Columns, this.AutoRemoveColumnsAndDetailConfigurations ); this.GenerateColumnsFromItemsSourceFields(); DataGridCollectionView dataGridCollectionView = this.ItemsSource as DataGridCollectionView; if( dataGridCollectionView != null ) { // We must keep a reference to the handler so that we can remove the same instance later on when unregistering from it. m_rootGroupChangedHandler = new WeakEventHandler<EventArgs>( this.OnDataGridCollectionView_RootGroupChanged ).Handler; dataGridCollectionView.RootGroupChanged += m_rootGroupChangedHandler; this.SetValue( DataGridControl.StatContextPropertyKey, dataGridCollectionView.RootGroup ); // We must keep a reference to the handler so that we can remove the same instance later on when unregistering from it. m_dataGridDetailDescriptionsChangedHandler = new WeakEventHandler<NotifyCollectionChangedEventArgs>( this.OnDataGridDetailDescriptionsChanged ).Handler; dataGridCollectionView.DetailDescriptions.CollectionChanged += m_dataGridDetailDescriptionsChangedHandler; DetailConfiguration.SynchronizeDetailConfigurations( dataGridCollectionView.DetailDescriptions, this.DetailConfigurations, this.AutoCreateDetailConfigurations, this.AutoCreateForeignKeyConfigurations, this.AutoRemoveColumnsAndDetailConfigurations ); // We must keep a reference to the handler so that we can remove the same instance later on when unregistering from it. m_proxyCollectionRefreshHandler = new WeakEventHandler<EventArgs>( this.OnDataGridCollectionView_ProxyCollectionRefresh ).Handler; dataGridCollectionView.ProxyCollectionRefresh += m_proxyCollectionRefreshHandler; // We must keep a reference to the handler so that we can remove the same instance later on when unregistering from it. m_proxyGroupDescriptionsChangedHandler = new WeakEventHandler<NotifyCollectionChangedEventArgs>( this.OnDataGridCollectionView_ProxyGroupDescriptionsChanged ).Handler; dataGridCollectionView.ProxyGroupDescriptionsChanged += m_proxyGroupDescriptionsChangedHandler; // We must keep a reference to the handler so that we can remove the same instance later on when unregistering from it. m_proxySortDescriptionsChangedHandler = new WeakEventHandler<NotifyCollectionChangedEventArgs>( this.OnDataGridCollectionView_ProxySortDescriptionsChanged ).Handler; dataGridCollectionView.ProxySortDescriptionsChanged += m_proxySortDescriptionsChangedHandler; // We must keep a reference to the handler so that we can remove the same instance later on when unregistering from it. m_proxyAutoFilterValuesChangedHandler = new WeakEventHandler<NotifyCollectionChangedEventArgs>( this.OnDataGridCollectionView_ProxyAutoFilterValuesChanged ).Handler; dataGridCollectionView.ProxyAutoFilterValuesChanged += m_proxyAutoFilterValuesChangedHandler; // We must keep a reference to the handler so that we can remove the same instance later on when unregistering from it. m_proxyApplyingFilterCriteriasHandler = new WeakEventHandler<EventArgs>( this.OnDataGridCollectionView_ProxyApplyingFilterCriterias ).Handler; dataGridCollectionView.ProxyApplyingFilterCriterias += m_proxyApplyingFilterCriteriasHandler; } else { DetailConfiguration.CleanupDetailConfigurations( this.DetailConfigurations, this.AutoRemoveColumnsAndDetailConfigurations ); this.ClearValue( DataGridControl.StatContextPropertyKey ); } DataGridVirtualizingCollectionViewBase virtualizingCollectionView = this.ItemsSource as DataGridVirtualizingCollectionViewBase; // Keep if the source is bound to DataGridVirtualizingCollectionView // to avoid preserving ContainerSizeState to avoid memory leaks this.IsBoundToDataGridVirtualizingCollectionViewBase = ( virtualizingCollectionView != null ); if( this.IsBoundToDataGridVirtualizingCollectionViewBase ) { // We must keep a reference to the handler so that we can remove the same instance later on when unregistering from it. m_connectionStateChangedHandler = new WeakEventHandler<EventArgs>( this.OnDataGridVirtualizingCollectionViewBase_ConnectionStateChanged ).Handler; virtualizingCollectionView.ConnectionStateChanged += m_connectionStateChangedHandler; // We must keep a reference to the handler so that we can remove the same instance later on when unregistering from it. m_connectionStateErrorHandler = new WeakEventHandler<EventArgs>( this.OnDataGridVirtualizingCollectionViewBase_ConnectionErrorChanged ).Handler; virtualizingCollectionView.ConnectionErrorChanged += m_connectionStateErrorHandler; } this.DataGridContext.NotifyItemsSourceChanged(); if( this.ItemsSourceChangeCompleted != null ) this.ItemsSourceChangeCompleted( this, EventArgs.Empty ); }
/// <summary> /// Sets the document node to null, but keeps the doc node path. /// </summary> protected void ClearDocNode() { if (_docNodeRef == null) return; OnBeforeClearDocNode(); if (null != _weakDocNodeTunneledEventHandler) { _weakDocNodeTunneledEventHandler.Remove(); _weakDocNodeTunneledEventHandler = null; } if (null != _weakDocNodeChangedHandler) { _weakDocNodeChangedHandler.Remove(); _weakDocNodeChangedHandler = null; } _docNodeRef = null; }
protected virtual void InternalInitializeWorksheetLayout(WorksheetLayout value) { if (null != _worksheetLayout) throw new ApplicationException("This controller is already controlling a layout"); if (null != _table) throw new ApplicationException("This controller is already controlling a table"); if (null == value) throw new ArgumentNullException("value"); if (null == value.DataTable) throw new ApplicationException("The DataTable of the WorksheetLayout is null"); _worksheetLayout = value; _table = _worksheetLayout.DataTable; var table = _table; // use local variable for anonymous method below _table.Changed += (_weakTableNameChangedHandler = new WeakEventHandler(this.EhTableNameChanged, x => table.Changed -= x)); OnTitleNameChanged(); }
public void IsHandlerFor_WrongObject_False() { var target = new Stub1(); var handler = new WeakEventHandler<Stub1, EventArgs>(target.Handler, eh => { }); Assert.IsFalse(handler.IsHandlerFor(new Stub1().Handler)); }
public void WhenDetachedWithNullDetachAction_ThenInvokesCallbackOnEvent() { var instance = this; var sender = new EventSource(); var invoked = false; var weakHandler = new WeakEventHandler<WeakEventListenerFixture, object, EventArgs>( instance, (i, s, e) => { invoked = true; }, null); sender.Event += weakHandler.OnEvent; weakHandler.Detach(); sender.FireEvent(new EventArgs()); Assert.IsTrue(invoked); }
/// <summary> /// Sets the watch on a node that is not our document node, but a node lower in the hierarchy. We watch both the Changed event and the TunneledEvent of this node. /// </summary> /// <param name="node">The node to watch.</param> protected virtual void SetWatchOnNode(IDocumentLeafNode node) { if (null == node) throw new ArgumentNullException(nameof(node)); if (null != _weakDocNodeChangedHandler) { _weakDocNodeChangedHandler.Remove(); _weakDocNodeChangedHandler = null; } if (null != _weakDocNodeTunneledEventHandler) { _weakDocNodeTunneledEventHandler.Remove(); _weakDocNodeTunneledEventHandler = null; } node.TunneledEvent += (_weakDocNodeTunneledEventHandler = new WeakActionHandler<object, object, TunnelingEventArgs>(EhWatchedNode_TunneledEvent, handler => node.TunneledEvent -= handler)); node.Changed += (_weakDocNodeChangedHandler = new WeakEventHandler(EhWatchedNode_Changed, handler => node.Changed -= handler)); #if DEBUG_DOCNODEPROXYLOGGING Current.Console.WriteLine("Start watching node <<{0}>> of total path <<{1}>>", AbsoluteDocumentPath.GetAbsolutePath(node), _docNodePath); #endif }
/// <summary> /// Sets the document node that is held by this proxy. /// </summary> /// <param name="value">The document node. If <c>docNode</c> implements <see cref="Main.IDocumentLeafNode" />, /// the document path is stored for this object in addition to the object itself.</param> public void SetDocNode(IDocumentLeafNode value) { if (null == value) throw new ArgumentNullException(nameof(value)); var oldValue = InternalDocumentNode; if (object.ReferenceEquals(oldValue, value)) return; if (!IsValidDocument(value)) throw new ArgumentException("This type of document is not allowed for the proxy of type " + this.GetType().ToString()); #if DOCNODEPROXY_CONCURRENTDEBUG _debug.Enqueue("START SetDocNode"); #endif if (null != _weakDocNodeChangedHandler) { _weakDocNodeChangedHandler.Remove(); _weakDocNodeChangedHandler = null; } if (null != _weakDocNodeTunneledEventHandler) { _weakDocNodeTunneledEventHandler.Remove(); _weakDocNodeTunneledEventHandler = null; } #if DOCNODEPROXY_CONCURRENTDEBUG _debug.Enqueue("MIDDL SetDocNode EventHandlers removed"); #endif if (oldValue != null) { ClearDocNode(); } InternalDocumentPath = Main.AbsoluteDocumentPath.GetAbsolutePath(value); _docNodeRef = new WeakReference(value); #if DEBUG_DOCNODEPROXYLOGGING Current.Console.WriteLine("DocNodeProxy.SetDocNode, path is <<{0}>>", _docNodePath); #endif InternalCheckAbsolutePath(); value.TunneledEvent += (_weakDocNodeTunneledEventHandler = new WeakActionHandler<object, object, TunnelingEventArgs>(EhDocNode_TunneledEvent, handler => value.TunneledEvent -= handler)); value.Changed += (_weakDocNodeChangedHandler = new WeakEventHandler(EhDocNode_Changed, handler => value.Changed -= handler)); OnAfterSetDocNode(); EhSelfChanged(new Main.InstanceChangedEventArgs(oldValue, value)); #if DOCNODEPROXY_CONCURRENTDEBUG _debug.Enqueue("STOP SetDocNode"); #endif }
/// <summary> /// Disposing this instance is special - we must not dispose the reference this instance holds. /// Instead, we remove all references to the holded document node and also all event handlers- /// </summary> /// <param name="isDisposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected override void Dispose(bool isDisposing) { if (null != _weakDocNodeChangedHandler) { _weakDocNodeChangedHandler.Remove(); _weakDocNodeChangedHandler = null; } if (null != _weakDocNodeTunneledEventHandler) { _weakDocNodeTunneledEventHandler.Remove(); _weakDocNodeTunneledEventHandler = null; } _docNodeRef = null; #if DEBUG_DOCNODEPROXYLOGGING Current.Console.WriteLine("DocNodeProxy.Dispose, path was >>>{0}<<<", _docNodePath); #endif _docNodePath = null; base.Dispose(isDisposing); }
/// <summary> /// Sets the watch on a node that is not our document node, but a node lower in the hierarchy. We watch both the Changed event and the TunneledEvent of this node. /// </summary> /// <param name="node">The node to watch.</param> protected virtual void SetWatchOnNode(IDocumentLeafNode node) { #if DOCNODEPROXY_CONCURRENTDEBUG int debugUsn = System.Threading.Interlocked.Increment(ref _debugUSN); _debug.Enqueue("START SetWatchOnNode " + debugUsn.ToString()); #endif if (null == node) throw new ArgumentNullException(nameof(node)); if (null != _weakDocNodeChangedHandler) { _weakDocNodeChangedHandler.Remove(); _weakDocNodeChangedHandler = null; } if (null != _weakDocNodeTunneledEventHandler) { _weakDocNodeTunneledEventHandler.Remove(); _weakDocNodeTunneledEventHandler = null; } node.TunneledEvent += (_weakDocNodeTunneledEventHandler = new WeakActionHandler<object, object, TunnelingEventArgs>(EhWatchedNode_TunneledEvent, handler => node.TunneledEvent -= handler)); node.Changed += (_weakDocNodeChangedHandler = new WeakEventHandler(EhWatchedNode_Changed, handler => node.Changed -= handler)); #if DEBUG_DOCNODEPROXYLOGGING Current.Console.WriteLine("Start watching node <<{0}>> of total path <<{1}>>", AbsoluteDocumentPath.GetAbsolutePath(node), _docNodePath); #endif #if DOCNODEPROXY_CONCURRENTDEBUG _debug.Enqueue("STOP SetWatchOnNode " + debugUsn.ToString() + (_docNodeRef == null).ToString()); #endif }