/// <summary> /// Attaches a child <see cref="IViewModel"/> to a parent <see cref="IViewModel"/>. /// If the child has already been attached, the newer instance will be attached instead of the previous instance. /// By being attached, the child will be disposed when the parent is disposed. /// Both also share the same <see cref="IViewModelView"/>. /// </summary> /// <remarks>The previous instance will be disposed when replaced.</remarks> /// <param name="viewModel">The parent <see cref="IViewModel"/>.</param> /// <param name="childViewModel">The child <see cref="IViewModel"/> to detach.</param> /// <param name="name">The child ViewModel's name. This defaults to <paramref name="childViewModel"/>.Name when not provided.</param> public static TChildViewModel AttachOrReplaceChild <TChildViewModel>(this IViewModel viewModel, TChildViewModel childViewModel, string name = null) where TChildViewModel : IViewModel { name = name ?? childViewModel.Name; if (viewModel.TryGetDisposable(name, out var instance)) { viewModel.DetachChild((IViewModel)instance, name); instance.Dispose(); } return(viewModel.AttachChild(childViewModel, name)); }
/// <summary> /// Gets the child of this <see cref="IViewModel"/> for the specified <paramref name="name"/>. /// If the child doesn't exist, it is created and attached using <paramref name="childViewModelProvider"/>. /// </summary> /// <typeparam name="TChildViewModel">The type of child ViewModel.</typeparam> /// <param name="viewModel">The parent <see cref="IViewModel"/>.</param> /// <param name="childViewModelProvider">The factory to the child <see cref="IViewModel"/>.</param> /// <param name="name">The child ViewModel's name.</param> /// <returns>The attached child <see cref="IViewModel"/>. Default of <typeparamref name="TChildViewModel"/> is returned if the <see cref="IViewModel"/> is disposed.</returns> public static TChildViewModel GetChild <TChildViewModel>( this IViewModel viewModel, Func <TChildViewModel> childViewModelProvider, [CallerMemberName] string name = null ) where TChildViewModel : IViewModel { if (viewModel.IsDisposed) { return(default(TChildViewModel)); } if (!viewModel.TryGetDisposable <TChildViewModel>(name, out var childViewModel)) { childViewModel = viewModel.AttachChild(childViewModelProvider(), name); } return(childViewModel); }