| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="ChildItemViewModel.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Diagnostics.CodeAnalysis; |
| | | 9 | | using MyNet.UI.Commands; |
| | | 10 | | |
| | | 11 | | namespace MyNet.UI.ViewModels.Crud; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Item view model that follows a parent <see cref="IItemViewModel{T}"/> and updates when the parent's item changes. |
| | | 15 | | /// </summary> |
| | | 16 | | /// <typeparam name="T">The item type.</typeparam> |
| | | 17 | | /// <remarks> |
| | | 18 | | /// Initializes a new instance of the <see cref="ChildItemViewModel{T}"/> class. |
| | | 19 | | /// </remarks> |
| | 0 | 20 | | public abstract class ChildItemViewModel<T>(ICommandFactory? commandFactory = null) : ItemViewModel<T>(commandFactory) |
| | | 21 | | { |
| | | 22 | | [SuppressMessage("Usage", "CA2213:Disposable fields should be disposed", Justification = "Disposed in Cleanup.")] |
| | | 23 | | private IDisposable? _parentSubscription; |
| | | 24 | | |
| | | 25 | | /// <summary> |
| | | 26 | | /// Attaches to a parent item view model. |
| | | 27 | | /// </summary> |
| | | 28 | | public virtual void Attach(IItemViewModel<T> parent) |
| | | 29 | | { |
| | 0 | 30 | | ArgumentNullException.ThrowIfNull(parent); |
| | | 31 | | |
| | 0 | 32 | | Detach(); |
| | 0 | 33 | | SetItem(parent.Item); |
| | 0 | 34 | | _parentSubscription = parent.ObserveItemChanged(OnParentItemChanged); |
| | 0 | 35 | | } |
| | | 36 | | |
| | | 37 | | /// <summary> |
| | | 38 | | /// Detaches from the parent item view model. |
| | | 39 | | /// </summary> |
| | | 40 | | public virtual void Detach() |
| | | 41 | | { |
| | 0 | 42 | | _parentSubscription?.Dispose(); |
| | 0 | 43 | | _parentSubscription = null; |
| | 0 | 44 | | } |
| | | 45 | | |
| | | 46 | | /// <summary> |
| | | 47 | | /// Called when the parent's item changes. |
| | | 48 | | /// </summary> |
| | 0 | 49 | | protected virtual void OnParentItemChanged(T? item) => SetItem(item); |
| | | 50 | | |
| | | 51 | | /// <inheritdoc /> |
| | | 52 | | protected override void DisposeManagedResources() |
| | | 53 | | { |
| | 0 | 54 | | Detach(); |
| | 0 | 55 | | base.DisposeManagedResources(); |
| | 0 | 56 | | } |
| | | 57 | | } |
| | | 58 | | |