| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="EventBehavior.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | using MyNet.Metadata; |
| | | 10 | | using MyNet.Observable.Behaviors.Metadata.Features; |
| | | 11 | | |
| | | 12 | | namespace MyNet.Observable.Behaviors; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Provides functionality to raise events and notify property changes for properties that are associated with a specifi |
| | | 16 | | /// </summary> |
| | | 17 | | /// <param name="owner">The owner object of this behavior.</param> |
| | 180 | 18 | | public abstract class EventBehavior<TOwner, TEvent>(TOwner owner) : SuspendableBehavior<TOwner>(owner) |
| | | 19 | | where TOwner : ObservableObject |
| | | 20 | | where TEvent : class |
| | | 21 | | { |
| | | 22 | | /// <summary> |
| | | 23 | | /// Raises an event of the specified type and notifies property changes for all properties that are associated with |
| | | 24 | | /// </summary> |
| | | 25 | | /// <param name="evt">The event instance to be raised.</param> |
| | | 26 | | protected void RaiseEvent(TEvent evt) |
| | | 27 | | { |
| | 258 | 28 | | if (IsDisposed || IsSuspended) |
| | 0 | 29 | | return; |
| | | 30 | | |
| | 804 | 31 | | foreach (var property in GetEventReactionProperties(Owner.GetType())) |
| | | 32 | | { |
| | 144 | 33 | | Owner.NotifyPropertyChanged(property); |
| | | 34 | | } |
| | | 35 | | |
| | 258 | 36 | | switch (Owner) |
| | | 37 | | { |
| | | 38 | | case IEventAware<TEvent> aware: |
| | 135 | 39 | | aware.OnEvent(evt); |
| | 135 | 40 | | break; |
| | | 41 | | case IAsyncEventAware<TEvent> asyncAware: |
| | 3 | 42 | | _ = asyncAware.OnEventAsync(evt); |
| | | 43 | | break; |
| | | 44 | | } |
| | 3 | 45 | | } |
| | | 46 | | |
| | | 47 | | private static IEnumerable<string> GetEventReactionProperties(Type ownerType) |
| | | 48 | | { |
| | 258 | 49 | | var seen = new HashSet<string>(StringComparer.Ordinal); |
| | | 50 | | |
| | 1842 | 51 | | for (var current = ownerType; current is not null && typeof(ObservableObject).IsAssignableFrom(current); current |
| | | 52 | | { |
| | 1614 | 53 | | foreach (var property in MetadataRegistry.Get(current).WithFeature<EventReactionFeature>(x => x.Events.Conta |
| | | 54 | | { |
| | 144 | 55 | | if (seen.Add(property)) |
| | 144 | 56 | | yield return property; |
| | | 57 | | } |
| | | 58 | | } |
| | 258 | 59 | | } |
| | | 60 | | } |
| | | 61 | | |