Skip to content

Instantly share code, notes, and snippets.

@xakpc
Created October 1, 2020 17:22
Show Gist options
  • Save xakpc/6d15b7b10ac9d01fcf9dbe30e89fcde8 to your computer and use it in GitHub Desktop.
Save xakpc/6d15b7b10ac9d01fcf9dbe30e89fcde8 to your computer and use it in GitHub Desktop.
Blazor ContextComponentBase (for MVVM)
/// <summary>
/// ComponentBase with DataContext
/// </summary>
public class ContextComponentBase : ComponentBase
{
/// <summary>
///
/// </summary>
protected ViewModelBase DataContext { get; set; }
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
if (DataContext == null) return;
if (!DataContext.Initialized) // do once
{
await DataContext.InitializeAsync();
DataContext.PropertyChanged += (s, e) => StateHasChanged();
}
await base.OnInitializedAsync();
}
}
public class ViewModelBase : INotifyPropertyChanged
{
/// <summary>
/// Flag indicator if ViewModel was initialized. Set to true by InitializeAsync Method
/// Used to avoid double initialization for ServerPrerendered mode
/// </summary>
public bool Initialized { get; set; }
/// <summary>
/// Initialize view model
/// </summary>
/// <returns></returns>
/// <remarks>This method should not use any JSInterop if render mode is ServerPrerendered</remarks>
public virtual Task InitializeAsync()
{
Initialized = true;
return Task.CompletedTask;
}
/// <summary>
///
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
///
/// </summary>
/// <param name="propertyName"></param>
[NotifyPropertyChangedInvocator]
// ReSharper disable once UnusedMember.Global
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
@ptirouz
Copy link

ptirouz commented Oct 20, 2020

Hi, I am very interested in your work.
I would like to test but I cannot find the namespace for [NotifyPropertyChangedInvocator] (I am in .net Standard 2.1)

Regards,

Christophe

@xakpc
Copy link
Author

xakpc commented Oct 20, 2020

@ptirouz this is an attribute which is added by ReSharper
it's used by ReSharper to easily generate properties with change notification
You can safely delete it.

@ptirouz
Copy link

ptirouz commented Oct 21, 2020

Thanks !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment