### Install Avalonia Templates
Source: https://caliburnmicro.com/documentation/AvaloniaUI
Installs the Avalonia UI project templates using the .NET CLI.
```bash
dotnet new install Avalonia.Templates
```
--------------------------------
### Install .NET MAUI Workload
Source: https://caliburnmicro.com/documentation/dotnet-maui
Installs the necessary .NET MAUI workload for Visual Studio. Use this command if you don't have MAUI installed.
```bash
dotnet workload install maui
```
--------------------------------
### Example: Custom Namespace and View Mapping
Source: https://caliburnmicro.com/documentation/custom-conventions
This example demonstrates setting up a custom type mapping. It captures a namespace fragment and uses it to transform the source namespace to a target namespace, resolving a ViewModel to a View with a custom convention.
```csharp
//Capture namespace fragment preceding "ViewModels." as "nsbefore"
string subns = RegExHelper.NamespaceToRegEx("ViewModels.");
string rxrep = RegExHelper.GetNamespaceCaptureGroup("nsbefore") + subns;
//Output the namespace fragment after "Views." in the target namespace
string rxtgt = @"Views.${nsbefore}";
ViewLocator.AddTypeMapping(rxrep, null, rxtgt);
//Resolves: MyApp.Some.Name.Space.ViewModels.TestViewModel -> Views.MyApp.Some.Name.Space.TestView
```
--------------------------------
### Custom Namespace Mapping Examples
Source: https://caliburnmicro.com/documentation/custom-conventions
Demonstrates custom namespace mappings for Spanish conventions and wildcard usage. These examples show how to resolve ViewModels to Views and vice-versa with custom namespace structures.
```csharp
//Add support for Spanish namespaces
ViewLocator.AddSubNamespaceMapping("ModelosDeVistas", "Vistas");
//Resolves: MiProyecto.ModelosDeVistas.Clientes.ClienteViewModel -> MiProyecto.Vistas.Clientes.ClienteView
ViewModelLocator.AddSubNamespaceMapping("Vistas", "ModelosDeVistas");
//Resolves: MiProyecto.Vistas.Clientes.ClienteView -> MiProyecto.ModelosDeVistas.Clientes.ClienteViewModel
//Wildcard subnamespace mapping
ViewLocator.AddSubNamespaceMapping("*.ViewModels", "ExtLib.Views");
//Resolves: MyCompany.MyApp.SomeNamespace.ViewModels.CustomerViewModel -> ExtLib.Views.CustomerView
ViewLocator.AddSubNamespaceMapping("ViewModels.*", "Views");
//Resolves: MyApp.ViewModels.Some.Name.Space.CustomerViewModel -> MyApp.Views.CustomerView
ViewLocator.AddSubNamespaceMapping("MyApp.*.ViewModels", "ExtLib.Views");
//Resolves: MyCompany.MyApp.SomeNamespace.ViewModels.CustomerViewModel -> MyCompany.ExtLib.Views.CustomerView
```
--------------------------------
### Get .NET Version
Source: https://caliburnmicro.com/documentation/build
Determine your installed .NET SDK version. This is useful for troubleshooting project loading issues.
```bash
dotnet --version
```
--------------------------------
### Install Caliburn.Micro Package
Source: https://caliburnmicro.com/documentation/nuget
Use this command in the Package Manager Console to install the Caliburn.Micro NuGet package.
```powershell
PM> Install-Package Caliburn.Micro
```
--------------------------------
### Applying Custom Window Settings
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/AddDialogToShellView
Example of creating dynamic settings for a window, including startup location, resize mode, minimum width, title, and icon, before showing it using the WindowManager.
```csharp
dynamic settings = new ExpandoObject();
settings.WindowStartupLocation = WindowStartupLocation.CenterOwner;
settings.ResizeMode = ResizeMode.NoResize;
settings.MinWidth = 450;
settings.Title = "My New Window";
settings.Icon = new BitmapImage( new Uri( "pack://application:,,,/MyApplication;component/Assets/myicon.ico" ) );
IWindowManager manager = new WindowManager();
manager.ShowDialog( myViewModel, null, settings );
```
--------------------------------
### App.xaml with Bootstrapper Resource
Source: https://caliburnmicro.com/documentation/configuration
This XAML snippet shows how to integrate the HelloBootstrapper into the application's resources. This ensures the bootstrapper runs when the application starts.
```xaml
```
--------------------------------
### Complete Bootstrapper Implementation
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/Bootstrapper
A complete example of the Bootstrapper class, including necessary using statements, constructor, and the overridden OnStartup method for .Net 5.0. For .NetCore 3.1, an additional using statement for Caliburn.Micro might be required.
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro.Tutorial.Wpf.ViewModels;
using System.Windows;
namespace Caliburn.Micro.Tutorial.Wpf
{
public class Bootstrapper: BootstrapperBase
{
public Bootstrapper()
{
Initialize();
}
protected override async void OnStartup(object sender, StartupEventArgs e)
{
await DisplayRootViewForAsync(typeof(ShellViewModel));
}
}
}
```
--------------------------------
### Custom Namespace Mapping Examples
Source: https://caliburnmicro.com/documentation/custom-conventions
Illustrates various ways to use AddNamespaceMapping, including appending targets to sources, standard explicit mappings, one-to-many mappings, and wildcard mappings.
```csharp
//"Append target to source" mapping
//Null string or string.Empty passed as source namespace is special case to allow this
//Note the need to prepend target namespace with "." to make this work
ViewLocator.AddNamespaceMapping("", ".Views");
//Resolves: MyProject.Customers.CustomerViewModel -> MyProject.Customers.Views.CustomerView
```
```csharp
//Standard explicit namespace mapping
ViewLocator.AddNamespaceMapping("MyProject.ViewModels.Customers", "MyClient1.Views");
//Resolves: MyProject.ViewModels.CustomerViewModel -> MyClient1.Views.CustomerView
```
```csharp
//One to many explicit namespace mapping
ViewLocator.AddNamespaceMapping("MyProject.ViewModels.Customers", new string[] { "MyClient1.Views", "MyProject.Views" } );
//Resolves: MyProject.ViewModels.CustomerViewModel -> {MyClient1.Views.CustomerView, MyProject.Views.CustomerView }
```
```csharp
//Wildcard mapping
ViewLocator.AddNamespaceMapping("*.ViewModels.Customers.*", "MyClient1.Customers.Views");
//Resolves: MyProject.ViewModels.Customers.CustomerViewModel -> MyClient1.Customers.Views.CustomerView
// MyProject.More.ViewModels.Customers.MasterViewModel -> MyClient1.Customers.Views.MasterView
// MyProject.ViewModels.Customers.More.OrderHistoryViewModel -> MyClient1.Customers.Views.OrderHistoryView
```
--------------------------------
### Constructor Injection Example
Source: https://caliburnmicro.com/documentation/simple-container
Demonstrates constructor injection where a service (IWindowManager) is a required dependency for a class (ShellViewModel). The container resolves and injects the dependency upon construction.
```csharp
public class ShellViewModel {
private readonly IWindowManager _windowManager;
public ShellViewModel(IWindowManager windowManager) {
_windowManager = windowManager;
}
}
```
--------------------------------
### Complete ShellViewModel Example
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/CategoryEditorHookup
This is the complete ShellViewModel, incorporating the EditCategories method and the OnViewLoaded override for invoking the category editor on application startup.
```csharp
using System.Threading;
using System.Threading.Tasks;
namespace Caliburn.Micro.Tutorial.Wpf.ViewModels
{
public class ShellViewModel : Conductor
{
protected async override void OnViewLoaded(object view)
{
base.OnViewLoaded(view);
await EditCategories();
}
public async Task EditCategories()
{
var viewmodel = IoC.Get();
await ActivateItemAsync(viewmodel, new CancellationToken());
}
}
}
```
--------------------------------
### Example Markup for Conventions
Source: https://caliburnmicro.com/documentation/conventions
This XAML demonstrates how Message.Attach can be used to declare an action on a Button that references a TextBox element.
```xaml
```
--------------------------------
### Coroutine Event Example
Source: https://caliburnmicro.com/documentation/event-aggregator
Example of an event that supports coroutine execution. It defines Activate and DoWork methods, each returning an IResult.
```csharp
public class EventWithCoroutine {
public IResult Activate() {
return new TaskResult(Task.Factory.StartNew(() => {
// Activate logic
}));
}
public IResult DoWork() {
return new TaskResult(Task.Factory.StartNew(() => {
// Do work logic
}));
}
}
```
--------------------------------
### Update App.axaml.cs for Bootstrapper Initialization
Source: https://caliburnmicro.com/documentation/AvaloniaUI
Modifies the App.axaml.cs file to initialize the Caliburn.Micro bootstrapper when the Avalonia application starts.
```csharp
public partial class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
public override void OnFrameworkInitializationCompleted()
{
base.OnFrameworkInitializationCompleted();
new Bootstrapper();
}
}
```
--------------------------------
### Configure Global.json SDK Version
Source: https://caliburnmicro.com/documentation/build
Update the 'sdk.version' in the Global.json file to match your installed .NET SDK version to resolve project loading errors.
```json
{
"sdk": {
"version": "3.1.101"
},
"msbuild-sdks": {
"MSBuild.Sdk.Extras": "2.0.54"
}
}
```
```json
{
"sdk": {
"version": "3.1.402"
},
"msbuild-sdks": {
"MSBuild.Sdk.Extras": "2.0.54"
}
}
```
--------------------------------
### Configure Type Mapping for Spanish Language and Semantics
Source: https://caliburnmicro.com/documentation/custom-conventions
Set up type mapping conventions for Spanish language, including custom namespaces, ViewModel suffixes, and view suffix lists. This example demonstrates internationalization of naming conventions.
```csharp
var config = new TypeMappingConfiguration()
{
DefaultSubNamespaceForViewModels = "ModelosDeVistas",
DefaultSubNamespaceForViews = "Vistas",
ViewModelSuffix = "ModeloDeVista",
ViewSuffixList = new List(new string[] { "Vista", "Pagina" }),
NameFormat = "{1}{0}",
IncludeViewSuffixInViewModelNames = false
};
ViewLocator.ConfigureTypeMappings(config);
ViewModelLocator.ConfigureTypeMappings(config);
```
--------------------------------
### Configure Caliburn.Micro in App.xaml.cs for WinUI3
Source: https://caliburnmicro.com/documentation/WinUI3
Modify App.xaml.cs to inherit from CaliburnApplication, initialize the container, register services, and set up navigation. This code demonstrates the typical setup for a WinUI3 application using Caliburn.Micro.
```csharp
using System;
using System.Collections.Generic;
using Caliburn.Micro;
using Microsoft.UI.Xaml.Controls;
using Setup.WinUI3.ViewModels;
using Setup.WinUI3.Views;
using Windows.ApplicationModel.Activation;
// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.
namespace Setup.WinUI3
{
///
/// Provides application-specific behavior to supplement the default Application class.
///
public partial class App : CaliburnApplication
{
private WinRTContainer container = new WinRTContainer();
///
/// Initializes the singleton application object. This is the first line of authored code
/// executed, and as such is the logical equivalent of main() or WinMain().
///
public App()
{
Initialize();
this.InitializeComponent();
}
protected override void Configure()
{
container.RegisterWinRTServices();
container.PerRequest();
}
protected override void PrepareViewFirst(Frame rootFrame)
{
container.RegisterNavigationService(rootFrame);
}
///
/// Invoked when the application is launched normally by the end user. Other entry points
/// will be used such as when the application is launched to open a specific file.
///
/// Details about the launch request and process.
protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
{
if (args.UWPLaunchActivatedEventArgs.PreviousExecutionState == ApplicationExecutionState.Running)
return;
DisplayRootView();
}
protected override object GetInstance(Type service, string key)
{
return container.GetInstance(service, key);
}
protected override IEnumerable GetAllInstances(Type service)
{
return container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
container.BuildUp(instance);
}
}
}
```
--------------------------------
### Simple TabViewModel Implementation
Source: https://caliburnmicro.com/documentation/composition
A basic C# class that inherits from Caliburn.Micro's Screen, serving as a ViewModel for a tab in the MDI application. It requires no additional logic for this simple example.
```C#
namespace Caliburn.Micro.SimpleMDI {
public class TabViewModel : Screen {}
}
```
--------------------------------
### Filtering a Collection of Service Instances
Source: https://caliburnmicro.com/documentation/service-locator
Example of using LINQ with IoC.GetAll() to find a specific service instance within a collection based on its type. This operation occurs after all instances have been instantiated.
```csharp
var viewModel = IoC.GetAll().FirstOrDefault(vm => vm.GetType() == typeof(ShellViewModel));
```
--------------------------------
### Configure Caliburn.Micro Bootstrapper with IoC Container
Source: https://caliburnmicro.com/documentation/bootstrapper
Override the Configure method to set up your IoC container, register services like IWindowManager and IEventAggregator, and define view models. This example uses the built-in SimpleContainer.
```csharp
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
public class SimpleBootstrapper : BootstrapperBase
{
private SimpleContainer container;
public SimpleBootstrapper()
{
Initialize();
}
protected override void Configure()
{
container = new SimpleContainer();
container.Singleton();
container.Singleton();
container.PerRequest();
}
protected override object GetInstance(Type service, string key)
{
return container.GetInstance(service, key);
}
protected override IEnumerable GetAllInstances(Type service)
{
return container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
container.BuildUp(instance);
}
protected override void OnStartup(object sender, StartupEventArgs e)
{
DisplayRootViewFor();
}
protected override IEnumerable SelectAssemblies()
{
return new[] { Assembly.GetExecutingAssembly() };
}
}
```
--------------------------------
### Injecting IoC Functionality with SimpleContainer
Source: https://caliburnmicro.com/documentation/service-locator
Example of a custom Bootstrapper that injects functionality into IoC using Caliburn.Micro's SimpleContainer. This is required for IoC to work correctly at the framework level.
```csharp
public class CustomBootstrapper : Bootstrapper {
private SimpleContainer _container = new SimpleContainer();
//...
protected override object GetInstance(Type service, string key) {
return _container.GetInstance(service, key);
}
protected override IEnumerable GetAllInstances(Type service) {
return _container.GetAllInstances(service);
}
protected override void BuildUp(object instance) {
_container.BuildUp(instance);
}
//...
}
```
--------------------------------
### Invoke Category Editor Method
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/CategoryEditorHookup
Create a method in ShellViewModel to get and activate the CategoryViewModel. Caliburn.Micro's IoC container is used here; a custom container setup will be covered later. Ensure the ContentControl in ShellView is named 'ActiveItem' for Caliburn.Micro's convention.
```csharp
public Task EditCategories()
{
var viewmodel = IoC.Get();
return ActivateItemAsync(viewmodel, new CancellationToken());
}
```
--------------------------------
### Configure Container with Singletons and ViewModels
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/SimpleContainer
Override the Configure method to set up the container, registering singletons for IWindowManager and IEventAggregator, and registering ViewModels per request using reflection.
```csharp
protected override void Configure()
{
_container.Instance(_container);
_container
.Singleton()
.Singleton();
foreach(var assembly in SelectAssemblies())
{
assembly.GetTypes()
.Where(type => type.IsClass)
.Where(type => type.Name.EndsWith("ViewModel"))
.ToList()
.ForEach(viewModelType => _container.RegisterPerRequest(
viewModelType, viewModelType.ToString(), viewModelType));
}
}
```
--------------------------------
### Page ViewModels
Source: https://caliburnmicro.com/documentation/composition
Represents simple view models for different pages. PageTwoViewModel includes an example of overriding OnActivate.
```csharp
public class PageOneViewModel : Screen {}
public class PageTwoViewModel : Screen {
protected override void OnActivate() {
MessageBox.Show("Page Two Activated"); //Don't do this in a real VM.
base.OnActivate();
}
}
```
--------------------------------
### Injecting Services into a Locally Created Instance
Source: https://caliburnmicro.com/documentation/service-locator
Demonstrates how to use IoC.BuildUp() to inject services into an instance that was created manually, rather than through the dependency container. The specific injection mechanism depends on the implementation provided to the BuildUp field.
```csharp
var viewModel = new LocallyCreatedViewModel();
IoC.BuildUp(viewModel);
```
--------------------------------
### Configure Caliburn.Micro in App.xaml.cs
Source: https://caliburnmicro.com/documentation/windows-runtime
Implement the App.xaml.cs file to configure Caliburn.Micro's WinRT container, register services, and prepare the application for view-first navigation. This involves overriding methods like Configure, GetInstance, GetAllInstances, BuildUp, PrepareViewFirst, and OnLaunched.
```csharp
using System;
using System.Collections.Generic;
using Caliburn.Micro.WinRT.Sample.Views;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml.Controls;
namespace Caliburn.Micro.WinRT.Sample
{
public sealed partial class App
{
private WinRTContainer container;
public App()
{
InitializeComponent();
}
protected override void Configure()
{
container = new WinRTContainer();
container.RegisterWinRTServices();
//TODO: Register your view models at the container
}
protected override object GetInstance(Type service, string key)
{
var instance = container.GetInstance(service, key);
if (instance != null)
return instance;
throw new Exception("Could not locate any instances.");
}
protected override IEnumerable GetAllInstances(Type service)
{
return container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
container.BuildUp(instance);
}
protected override void PrepareViewFirst(Frame rootFrame)
{
container.RegisterNavigationService(rootFrame);
}
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
if (args.PreviousExecutionState == ApplicationExecutionState.Running)
return;
DisplayRootView();
}
}
}
```
--------------------------------
### HelloBootstrapper Class
Source: https://caliburnmicro.com/documentation/configuration
This class extends BootstrapperBase and initializes the Caliburn.Micro framework. It overrides OnStartup to display the root view model, ShellViewModel.
```csharp
namespace Caliburn.Micro.Hello {
public class HelloBootstrapper : BootstrapperBase {
public HelloBootstrapper() {
Initialize();
}
protected override void OnStartup(object sender, StartupEventArgs e) {
DisplayRootViewFor();
}
}
}
```
--------------------------------
### Registering EventAggregator as a Singleton
Source: https://caliburnmicro.com/documentation/event-aggregator
Configures the EventAggregator as a singleton instance within the application's dependency injection container during the bootstrapper setup.
```csharp
public class Bootstrapper : BootstrapperBase {
private readonly SimpleContainer _container =
new SimpleContainer();
// ... Other Bootstrapper Config
protected override void Configure(){
_container.Singleton();
}
// ... Other Bootstrapper Config
}
```
--------------------------------
### Configure App.Xaml.cs for Root Project
Source: https://caliburnmicro.com/documentation/dotnet-maui
Configures the App.Xaml.cs file in the root project to initialize Caliburn.Micro and display the root view asynchronously.
```csharp
public partial class App : Caliburn.Micro.Maui.MauiApplication
{
public App()
{
InitializeComponent();
Initialize();
DisplayRootViewForAsync();
}
}
```
--------------------------------
### Update and Restore .NET MAUI Workloads
Source: https://caliburnmicro.com/documentation/dotnet-maui
Updates existing .NET MAUI workloads and restores them. Use this if you have an older version of MAUI installed.
```bash
dotnet workload update
dotnet workload restore
```
--------------------------------
### Implement Container Resolution Methods
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/SimpleContainer
Implement GetInstance, GetAllInstances, and BuildUp methods to enable the container to resolve dependencies and build up object instances.
```csharp
protected override object GetInstance(Type service, string key)
{
return _container.GetInstance(service, key);
}
protected override IEnumerable GetAllInstances(Type service)
{
return _container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
_container.BuildUp(instance);
}
```
--------------------------------
### Customize Singularize Function
Source: https://caliburnmicro.com/documentation/conventions
Replaces the default ConventionManager.Singularize function with one that utilizes the Humanizer library for more sophisticated pluralization handling. Ensure Humanizer is installed and referenced.
```csharp
ConventionManager.Singularize = original => original.Singularize(inputIsKnownToBePlural: false);
```
--------------------------------
### Display Root View in View First
Source: https://caliburnmicro.com/documentation/WinUI3
Override OnLaunched to call DisplayRootView with the type of the initial view to navigate to.
```csharp
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
DisplayRootView();
}
```
--------------------------------
### Register Navigation Service in View First
Source: https://caliburnmicro.com/documentation/WinUI3
Override PrepareViewFirst to register the navigation service with the container, passing the root frame.
```csharp
protected override void PrepareViewFirst(Frame rootFrame)
{
container.RegisterNavigationService(rootFrame);
}
```
--------------------------------
### TabControl XAML Example
Source: https://caliburnmicro.com/documentation/conventions
A simple XAML declaration for a TabControl named 'Items'. Caliburn.Micro applies conventions to automatically handleItemsSource, ItemTemplate, ContentTemplate, and SelectedItem binding.
```XAML
```
--------------------------------
### Caliburn.Micro Example Event Class
Source: https://caliburnmicro.com/documentation/cheat-sheet
A simple C# class representing an event that can be published and subscribed to via the Event Aggregator. It includes a constructor and a property to hold data.
```csharp
public class MyEvent {
public MyEvent(string myData) {
this.MyData = myData;
}
public string MyData { get; private set; }
}
```
--------------------------------
### Retrieving a Collection of Service Instances
Source: https://caliburnmicro.com/documentation/service-locator
Illustrates how to request a collection of all registered instances of a specific service type using IoC.GetAll(). LINQ can be used to filter the results, but be aware that all instances will have already been created.
```csharp
var viewModelCollection = IoC.GetAll();
```
--------------------------------
### View-First Bootstrapper Configuration
Source: https://caliburnmicro.com/documentation/actions
Override OnStartup to instantiate the ShellView and set it as the RootVisual when using View-First. This approach inherits from the non-generic BootstrapperBase.
```csharp
public class MefBootstrapper : BootstrapperBase
{
//same as before
protected override void OnStartup(object sender, StartupEventArgs e)
{
Application.RootVisual = new ShellView();
}
//same as before
}
```
--------------------------------
### Initialize SimpleContainer
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/SimpleContainer
Instantiate the SimpleContainer to manage dependencies within your application.
```csharp
private readonly SimpleContainer _container = new SimpleContainer();
```
--------------------------------
### Retrieving a Single Service Instance by Type
Source: https://caliburnmicro.com/documentation/service-locator
Demonstrates how to use IoC.Get() to retrieve a single service instance based on its type.
```csharp
var windowManager = IoC.Get();
```
--------------------------------
### Handle Instance Activation Event
Source: https://caliburnmicro.com/documentation/simple-container
Subscribe to the Activate event to perform custom initialization or operations on instances immediately after they are created by the container.
```csharp
class CustomBootstrapper : BootstrapperBase {
private SimpleContainer _container
...
protected override void Configure() {
...
_container.Activate += _OnInstanceActivation;
}
private void OnInstanceActivation(object instance) {
// Perform any custom operations
}
}
```
--------------------------------
### Retrieving a Single Service Instance by Type and Key
Source: https://caliburnmicro.com/documentation/service-locator
Shows how to retrieve a single service instance using both its type and a specific key. Note that key-based retrieval is not supported by all dependency injection containers.
```csharp
var windowManager = IoC.Get("windowManager");
```
--------------------------------
### Coroutine Action Example in ViewModel
Source: https://caliburnmicro.com/documentation/coroutines
Implement a ViewModel action that returns an IEnumerable to define a sequence of tasks. Each yield statement represents a step in the coroutine, pausing execution until the yielded IResult completes.
```csharp
using System.Collections.Generic;
using System.ComponentModel.Composition;
[Export(typeof(ScreenOneViewModel))]
public class ScreenOneViewModel
{
public IEnumerable GoForward()
{
yield return Loader.Show("Downloading...");
yield return new LoadCatalog("Caliburn.Micro.Coroutines.External.xap");
yield return Loader.Hide();
yield return new ShowScreen("ExternalScreen");
}
}
```
--------------------------------
### Register Instance Method Signature
Source: https://caliburnmicro.com/documentation/simple-container
Use RegisterInstance to register a pre-constructed object with the container against a specific type and optional key.
```csharp
void RegisterInstance(Type serviceType, string key, object instance);
```
--------------------------------
### Caliburn.Micro Coroutine Task Support
Source: https://caliburnmicro.com/documentation/async
The Coroutine class provides methods to execute asynchronous operations represented by Tasks. `BeginExecute` starts a coroutine with a callback, while `ExecuteAsync` returns a Task that completes when the coroutine finishes.
```csharp
public static class Coroutine {
public static void BeginExecute(
IEnumerator coroutine,
CoroutineExecutionContext context = null,
EventHandler callback = null) { }
public static Task ExecuteAsync(
IEnumerator coroutine,
CoroutineExecutionContext context = null) { }
}
```
--------------------------------
### Create Bootstrapper Class
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/Bootstrapper
Define the Bootstrapper class, ensuring it is public and inherits from BootstrapperBase. Include necessary using statements.
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Caliburn.Micro;
namespace Caliburn.Micro.Tutorial.Wpf
{
public class Bootstrapper: BootstrapperBase
{
}
}
```
--------------------------------
### Original App.xaml
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/App_Xaml
The default App.xaml file in a WPF project before modifications.
```xaml
```
--------------------------------
### Add GitHub NuGet Source
Source: https://caliburnmicro.com/documentation/nuget
Add the Caliburn.Micro GitHub NuGet feed as a source to your local NuGet configuration. Replace placeholders with your GitHub username and generated token.
```bash
dotnet nuget add source --username --password --store-password-in-clear-text --name "Caliburn.Micro github" "https://nuget.pkg.github.com/caliburn.micro/index.json"
```
--------------------------------
### Add Bootstrapper Constructor
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/Bootstrapper
Implement the constructor for the Bootstrapper class, calling the Initialize() method to set up Caliburn.Micro.
```csharp
public Bootstrapper()
{
Initialize();
}
```
--------------------------------
### Caliburn.Micro Bootstrapper Configuration
Source: https://caliburnmicro.com/documentation/AvaloniaUI
Defines the application's bootstrapper class for Caliburn.Micro, configuring dependency injection and startup behavior.
```csharp
namespace AvaloniaApplication1
{
public class Bootstrapper : BootstrapperBase
{
private SimpleContainer _container = new SimpleContainer();
public Bootstrapper()
{
Initialize();
}
protected override void Configure()
{
_container.Instance(_container);
_container
.Singleton()
.Singleton();
_container
.PerRequest()
.PerRequest();
}
protected override async void OnStartup(object sender, ControlledApplicationLifetimeStartupEventArgs e)
{
await DisplayRootViewFor();
}
protected override object GetInstance(Type service, string key)
{
return _container.GetInstance(service, key);
}
protected override IEnumerable GetAllInstances(Type service)
{
return _container.GetAllInstances(service);
}
protected override void BuildUp(object instance)
{
_container.BuildUp(instance);
}
}
}
```
--------------------------------
### Configure App.xaml for Root Project
Source: https://caliburnmicro.com/documentation/dotnet-maui
Modifies the App.xaml file in the project root to use Caliburn.Micro.Maui's MauiApplication and define namespaces. Remember to replace 'MauiApp2' with your app's namespace.
```xml
```
--------------------------------
### Caliburn.Micro Short Syntax for Different Events
Source: https://caliburnmicro.com/documentation/cheat-sheet
Demonstrates how to attach different events, such as MouseEnter, to ViewModel actions using cal:Message.Attach.
```xaml
```
--------------------------------
### Modified App.xaml with Bootstrapper
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/App_Xaml
The final App.xaml file after removing StartupUri and adding the Bootstrapper as a resource. This configures the application to use Caliburn.Micro's bootstrapping mechanism.
```xaml
```
--------------------------------
### Explicit Event and Action Syntax with Message.Attach
Source: https://caliburnmicro.com/documentation/actions
Demonstrates the full syntax for Message.Attach, explicitly defining the event and the action to be executed, including passing the data context as a parameter.
```xaml
```
--------------------------------
### Activate Category Editor on Startup
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/CategoryEditorHookup
Override the OnViewLoaded method in ShellViewModel to asynchronously call EditCategories() when the ShellView is loaded. Do not use 'Task' as the return type for OnViewLoaded.
```csharp
protected async override void OnViewLoaded(object view)
{
base.OnViewLoaded(view);
await EditCategories();
}
```
--------------------------------
### Automated ViewModel Registration with Reflection
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/SimpleContainer
Automate the registration of all ViewModels in the executing assembly using reflection and LINQ. This approach registers ViewModels per request, creating a new instance each time.
```csharp
foreach(var assembly in SelectAssemblies())
{
assembly.GetTypes()
.Where(type => type.IsClass)
.Where(type => type.Name.EndsWith("ViewModel"))
.ToList()
.ForEach(viewModelType => _container.RegisterPerRequest(
viewModelType, viewModelType.ToString(), viewModelType));
}
```
--------------------------------
### Register Per Request
Source: https://caliburnmicro.com/documentation/simple-container
Handles per-request registration, creating a new instance for each request. Supports registration against a type, key, or both, with overloads for convenience.
```APIDOC
void RegisterPerRequest(Type serviceType, string key, Type implementation);
SimpleContainer PerRequest()
SimpleContainer PerRequest()
```
--------------------------------
### Add Caliburn.Micro.Maui Package from GitHub Feed
Source: https://caliburnmicro.com/documentation/nuget
Add the Caliburn.Micro.Maui package from the GitHub NuGet feed to your project. Ensure you are in the directory containing the csproj file.
```bash
dotnet add package Caliburn.Micro.Maui --version 5.0.183-beta --source "https://nuget.pkg.github.com/caliburn-micro/index.json"
```
--------------------------------
### Implement LoadCatalog IResult for dynamic XAP loading
Source: https://caliburnmicro.com/documentation/coroutines
This IResult implementation dynamically downloads and loads a XAP file using MEF's DeploymentCatalog. It handles the asynchronous download process and integrates the new catalog into the application's aggregate catalog upon completion.
```csharp
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.ReflectionModel;
using System.Linq;
public class LoadCatalog : IResult
{
static readonly Dictionary Catalogs = new Dictionary();
readonly string uri;
[Import]
public AggregateCatalog Catalog { get; set; }
public LoadCatalog(string relativeUri)
{
uri = relativeUri;
}
public void Execute(CoroutineExecutionContext context)
{
DeploymentCatalog catalog;
if(Catalogs.TryGetValue(uri, out catalog))
Completed(this, new ResultCompletionEventArgs());
else
{
catalog = new DeploymentCatalog(uri);
catalog.DownloadCompleted += (s, e) =>{
if(e.Error == null)
{
Catalogs[uri] = catalog;
Catalog.Catalogs.Add(catalog);
catalog.Parts
.Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly)
.Where(assembly => !AssemblySource.Instance.Contains(assembly))
.Apply(x => AssemblySource.Instance.Add(x));
}
else Loader.Hide().Execute(context);
Completed(this, new ResultCompletionEventArgs {
Error = e.Error,
WasCancelled = false
});
};
catalog.DownloadAsync();
}
}
public event EventHandler Completed = delegate { };
}
```
--------------------------------
### Register Instance
Source: https://caliburnmicro.com/documentation/simple-container
Allows registering a pre-constructed instance with the container. The `Instance` overload registers against the implementation's type.
```APIDOC
void RegisterInstance(Type serviceType, string key, object instance);
SimpleContainer Instance(TService instance)
```
--------------------------------
### WindowManager ShowDialogAsync Overload with Settings
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/AddDialogToShellView
Demonstrates the extended signature of ShowDialogAsync, allowing custom settings for the dialog window such as startup location, resize mode, minimum dimensions, title, and icon.
```csharp
public virtual async Task ShowDialogAsync(object rootModel, object context = null, IDictionary settings = null)
```
--------------------------------
### Add Bootstrapper Resource to App.xaml
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/App_Xaml
Add the Bootstrapper class as a local resource within the Application.Resources section. This replaces the StartupUri and allows the Bootstrapper to manage application startup.
```xaml
```
--------------------------------
### Configure MainApplication for Android
Source: https://caliburnmicro.com/documentation/dotnet-maui
Modifies the MainApplication class in the Android platform folder to inherit from CaliburnApplication and configure assemblies.
```csharp
[Application]
public class MainApplication : Caliburn.Micro.Maui.CaliburnApplication
{
public MainApplication(IntPtr handle, JniHandleOwnership ownership)
: base(handle, ownership)
{
Initialize();
}
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
protected override void Configure()
{
base.Configure();
}
protected override IEnumerable SelectAssemblies()
{
return new List() { typeof(App).Assembly };
}
}
```
--------------------------------
### ShellViewModel for Simple Navigation
Source: https://caliburnmicro.com/documentation/composition
Inherits from Conductor and manages navigation between PageOneViewModel and PageTwoViewModel by calling ActivateItem.
```csharp
public class ShellViewModel : Conductor {
public ShellViewModel() {
ShowPageOne();
}
public void ShowPageOne() {
ActivateItem(new PageOneViewModel());
}
public void ShowPageTwo() {
ActivateItem(new PageTwoViewModel());
}
}
```
--------------------------------
### Clone Caliburn.Micro Repository
Source: https://caliburnmicro.com/documentation/build
Use this command to clone the Caliburn.Micro project from its GitHub repository.
```bash
git clone https://github.com/Caliburn-Micro/Caliburn.Micro.git
```
--------------------------------
### Add Caliburn.Micro.Avalonia NuGet Package
Source: https://caliburnmicro.com/documentation/AvaloniaUI
Adds the Caliburn.Micro.Avalonia NuGet package to the project with a specific version and source.
```bash
dotnet add package Caliburn.Micro.Avalonia --version 5.0.183-beta --source "https://nuget.pkg.github.com/caliburn-micro/index.json"
```
--------------------------------
### Property Injection with BuildUp
Source: https://caliburnmicro.com/documentation/simple-container
Illustrates property injection where services are injected into an instance created outside the container using the BuildUp method. Note that property injection typically works only for interface types.
```csharp
...
var shellViewModel = new ShellViewModel();
_container.BuildUp(shellViewModel);
}
}
public class ShellViewModel {
public IEventAggregator EventAggregator { get; set; }
}
```
--------------------------------
### Add Caliburn.Micro.Maui NuGet Package
Source: https://caliburnmicro.com/documentation/dotnet-maui
Adds the Caliburn.Micro.Maui NuGet package to your solution from a specific GitHub package source. Ensure you are in the project's terminal directory.
```bash
dotnet add package Caliburn.Micro.Maui --version 5.0.183-beta --source "https://nuget.pkg.github.com/caliburn-micro/index.json"
```
--------------------------------
### AboutView.cs - Code-behind for Hyperlink Navigation
Source: https://caliburnmicro.com/documentation/Tutorials/WPF/DialogForm
Provides the code-behind for the About dialog, handling the hyperlink navigation event. Includes a workaround for .NET Core to open URIs using ProcessStartInfo.
```C#
using System.Diagnostics;
using System.Windows;
namespace Caliburn.Micro.Tutorial.Wpf.Views
{
public partial class AboutView : Window
{
public AboutView()
{
InitializeComponent();
}
private void Hyperlink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
{
// You need a workaround here for .Net Core:
// https://github.com/dotnet/runtime/issues/28005
var psi = new ProcessStartInfo
{
FileName = e.Uri.AbsoluteUri,
UseShellExecute = true
};
Process.Start(psi);
}
}
}
```