Created
October 1, 2020 17:22
-
-
Save xakpc/6d15b7b10ac9d01fcf9dbe30e89fcde8 to your computer and use it in GitHub Desktop.
Blazor ContextComponentBase (for MVVM)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks !