Skip to content

Instantly share code, notes, and snippets.

@mysteryx93
Last active June 19, 2023 15:35
Show Gist options
  • Save mysteryx93/7a47ee8b3dad35b9620ff5ea85d31386 to your computer and use it in GitHub Desktop.
Save mysteryx93/7a47ee8b3dad35b9620ff5ea85d31386 to your computer and use it in GitHub Desktop.
@typeparam TViewModel
<CascadingValue TValue="TViewModel" Value="ViewModel">
@ChildContent
</CascadingValue>
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using Microsoft.AspNetCore.Components;
using ThomasJaworski.ComponentModel;
// Using RecursiveChangeNotifier
// https://github.com/lostmsu/RecursiveChangeNotifier/
namespace WebStore.Shared
{
public partial class ViewModelRegion<TViewModel> : ComponentBase
where TViewModel : class, INotifyPropertyChanged
{
[Parameter]
public RenderFragment? ChildContent { get; set; }
[Parameter]
public TViewModel? ViewModel
{
get => _viewModel;
set
{
if (_changeListener != null)
{
_changeListener.Dispose();
_changeListener = null;
}
_viewModel = value;
if (_viewModel != null)
{
_changeListener = ChangeListener.Create(value);
_changeListener.PropertyChanged += ViewModel_PropertyChanged;
_changeListener.CollectionChanged += ViewModel_CollectionChanged;
}
}
}
private TViewModel? _viewModel;
private ChangeListener? _changeListener;
private void ViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) => InvokeAsync(() => StateHasChanged()).ConfigureAwait(false);
private void ViewModel_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) => InvokeAsync(() => StateHasChanged()).ConfigureAwait(false);
public void Dispose()
{
if (_changeListener != null)
{
_changeListener.Dispose();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment