Interface ILifecycleAware
- Namespace
- Crystal.Avalonia
- Assembly
- Crystal.Avalonia.dll
Defines lifecycle hooks for ViewModel initialization and cleanup when used with ViewModelLocator or ViewLocator.
public interface ILifecycleAware
Examples
public class MyViewModel : ObservableObject, ILifecycleAware
{
public async Task OnLoadedAsync(bool isFirstLoad)
{
if (!isFirstLoad) return;
await LoadDataAsync();
}
public Task OnUnloaded() => Task.CompletedTask;
}
Remarks
Both ViewModelLocator and ViewLocator subscribe to the View's
Loaded and Unloaded events when the DataContext implements this interface.
OnLoadedAsync(bool) is invoked on every Loaded. The isFirstLoad argument
is true only the first time that ViewModel instance is loaded.
Transient ViewModels therefore always see true; a singleton sees false on later visits.
OnUnloaded() is invoked on every Unload. Exceptions are caught and written to
Trace.
Methods
OnLoadedAsync(bool)
Called when the View is loaded and ready for interaction.
Task OnLoadedAsync(bool isFirstLoad)
Parameters
isFirstLoadbooltruethe first time this ViewModel instance is loaded;falseon subsequent loads of the same instance (for example a singleton after navigation).
Returns
OnUnloaded()
Called when the View is unloaded and no longer part of the visual tree. Invoked on every unload.
Task OnUnloaded()