Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@ptirouz 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

This comment has been minimized.

Copy link
Owner Author

@xakpc 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

This comment has been minimized.

Copy link

@ptirouz ptirouz commented Oct 21, 2020

Thanks !

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