https://github.com/reactiveui/reactiveui.sourcegenerators
Use source generators to generate objects.
https://github.com/reactiveui/reactiveui.sourcegenerators
Last synced: 4 months ago
JSON representation
Use source generators to generate objects.
- Host: GitHub
- URL: https://github.com/reactiveui/reactiveui.sourcegenerators
- Owner: reactiveui
- License: mit
- Created: 2023-04-06T17:52:28.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2024-10-03T15:36:22.000Z (8 months ago)
- Last Synced: 2024-10-07T00:15:57.745Z (8 months ago)
- Language: C#
- Size: 542 KB
- Stars: 25
- Watchers: 9
- Forks: 1
- Open Issues: 8
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ReactiveUI Source Generators Documentation
This documentation covers using ReactiveUI Source Generators to simplify and enhance the use of ReactiveUI objects.
- **Minimum Requirements**:
- **C# Version**: 12.0
- **Visual Studio Version**: 17.8.0
- **ReactiveUI Version**: 19.5.31+## Overview
ReactiveUI Source Generators automatically generate ReactiveUI objects to streamline your code. These Source Generators are designed to work with ReactiveUI V19.5.31+ and support the following features:
- `[Reactive]` With field and access modifiers, partial property support (C# 13 Visual Studio Version 17.12.0)
- `[ObservableAsProperty]` With field, method, Observable property and partial property support (C# 13 Visual Studio Version 17.12.0)
- `[ObservableAsProperty(ReadOnly = false)]` Removes readonly keyword from the generated helper field
- `[ObservableAsProperty(PropertyName = "ReadOnlyPropertyName")]`
- `[ObservableAsProperty(InitialValue = "Default Value")]` Only valid for partial properties using (C# 13 Visual Studio Version 17.12.0)
- `[ReactiveCommand]`
- `[ReactiveCommand(CanExecute = nameof(IObservableBoolName))]` with CanExecute
- `[ReactiveCommand(OutputScheduler = "RxApp.MainThreadScheduler")]` using a ReactiveUI Scheduler
- `[ReactiveCommand(OutputScheduler = nameof(_isheduler))]` using a Scheduler defined in the class
- `[ReactiveCommand][property: AttributeToAddToCommand]` with Attribute passthrough
- `[IViewFor(nameof(ViewModelName))]`
- `[RoutedControlHost("YourNameSpace.CustomControl")]`
- `[ViewModelControlHost("YourNameSpace.CustomControl")]`### Compatibility Notes
- For ReactiveUI versions **older than V19.5.31**, all `[ReactiveCommand]` options are supported except for async methods with a `CancellationToken`.
- For **.NET Framework 4.8 and older**, add [Polyfill by Simon Cropp](https://github.com/SimonCropp/Polyfill) or [PolySharp by Sergio Pedri](https://github.com/Sergio0694/PolySharp) to your project and set the `LangVersion` to 12.0 or later in your project file.For more information on analyzer codes, see the [analyzer codes documentation](https://github.com/reactiveui/ReactiveUI.SourceGenerators/blob/main/src/ReactiveUI.SourceGenerators/AnalyzerReleases.Shipped.md).
---
## Supported Attributes
### `[Reactive]`
Marks properties as reactive, generating getter and setter code.### `[ObservableAsProperty]`
Generates read-only properties backed by an `ObservableAsPropertyHelper` based on an `IObservable`.### `[ReactiveCommand]`
Generates commands, with options to add attributes or enable `CanExecute` functionality.### `[IViewFor]`
Links a view to a view model for data binding.### `[RoutedControlHost]` and `[ViewModelControlHost]`
Platform-specific attributes for control hosting in WinForms applications.## Historical Approach
### Read-Write Properties
Previously, properties were declared like this:```csharp
private string _name;
public string Name
{
get => _name;
set => this.RaiseAndSetIfChanged(ref _name, value);
}
```Before these Source Generators were available we used ReactiveUI.Fody.
With ReactiveUI.Fody the `[Reactive]` Attribute was placed on a Public Property with Auto get / set properties, the generated code from the Source Generator and the Injected code using Fody are very similar with the exception of the Attributes.```csharp
[Reactive]
public string Name { get; set; }
```## ObservableAsPropertyHelper properties
Similarly, to declare output properties, the code looks like this:
```csharp
public partial class MyReactiveClass : ReactiveObject
{
ObservableAsPropertyHelper _firstName;public MyReactiveClass()
{
_firstName = firstNameObservable
.ToProperty(this, x => x.FirstName);
}public string FirstName => _firstName.Value;
private IObservable firstNameObservable() => Observable.Return("Test");
}
```With ReactiveUI.Fody, you can simply declare a read-only property using the [ObservableAsProperty] attribute, using either option of the two options shown below.
```csharp
[ObservableAsProperty]
public string FirstName { get; }
```# Welcome to a new way - Source Generators
## Usage Reactive property `[Reactive]`
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
[Reactive]
private string _myProperty;
}
```### Usage Reactive property with set Access Modifier
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
[Reactive(SetModifier = AccessModifier.Protected)]
private string _myProperty;
}
```### Usage Reactive property with property Attribute pass through
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
[Reactive]
[property: JsonIgnore]
private string _myProperty;
}
```### Usage Reactive property from partial property
Partial properties are supported in C# 13 and Visual Studio 17.12.0 and later.
Both the getter and setter must be empty, and the `[Reactive]` attribute must be placed on the property.
Override and Virtual properties are supported.
Set Access Modifier is also supported on partial properties.```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
[Reactive]
public partial string MyProperty { get; set; }
}
```## Usage ObservableAsPropertyHelper `[ObservableAsProperty]`
ObservableAsPropertyHelper is used to create a read-only property from an IObservable. The generated code will create a backing field and a property that returns the value of the backing field. The backing field is initialized with the value of the IObservable when the class is instantiated.
A private field is created with the name of the property prefixed with an underscore. The field is initialized with the value of the IObservable when the class is instantiated. The property is created with the same name as the field without the underscore. The property returns the value of the field until initialized, then it returns the value of the IObservable.
You can define the name of the property by using the PropertyName parameter. If you do not define the PropertyName, the property name will be the same as the field name without the underscore.
### Usage ObservableAsPropertyHelper with Field
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
[ObservableAsProperty]
private string _myProperty = "Default Value";public MyReactiveClass()
{
_myPrpertyHelper = MyPropertyObservable()
.ToProperty(this, x => x.MyProperty);
}IObservable MyPropertyObservable() => Observable.Return("Test Value");
}
```### Usage ObservableAsPropertyHelper with Field and non readonly nullable OAPH field
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject, IActivatableViewModel
{
[ObservableAsProperty(ReadOnly = false)]
private string _myProperty = "Default Value";public MyReactiveClass()
{
this.WhenActivated(disposables =>
{
_myPrpertyHelper = MyPropertyObservable()
.ToProperty(this, x => x.MyProperty)
.DisposeWith(disposables);
});
}IObservable MyPropertyObservable() => Observable.Return("Test Value");
}
```### Usage ObservableAsPropertyHelper with Observable Property and specific PropertyName
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
[ObservableAsProperty(ReadOnly = false)]
private string _myProperty = "Default Value";public MyReactiveClass()
{
this.WhenActivated(disposables =>
{
_myPrpertyHelper = MyPropertyObservable()
.ToProperty(this, x => x.MyProperty)
.DisposeWith(disposables);
});
}IObservable MyPropertyObservable() => Observable.Return("Test Value");
}
```### Usage ObservableAsPropertyHelper with Observable Property and protected OAPH field
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
[ObservableAsProperty(UseProtected = true)]
private string _myProperty = "Default Value";public MyReactiveClass()
{
_myPrpertyHelper = MyPropertyObservable()
.ToProperty(this, x => x.MyProperty);
}IObservable MyPropertyObservable() => Observable.Return("Test Value");
}
```### Usage ObservableAsPropertyHelper with Observable Method
NOTE: This does not currently support methods with parameters
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
public MyReactiveClass()
{
// Initialize generated _myObservablePropertyHelper
// for the generated MyObservableProperty
InitializeOAPH();
}[ObservableAsProperty]
IObservable MyObservable() => Observable.Return("Test Value");
}
```### Usage ObservableAsPropertyHelper with Observable Method and specific PropertyName
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
public MyReactiveClass()
{
// Initialize generated _testValuePropertyHelper
// for the generated TestValueProperty
InitializeOAPH();
}[ObservableAsProperty(PropertyName = TestValueProperty)]
IObservable MyObservable() => Observable.Return("Test Value");
}
```### Usage ObservableAsPropertyHelper with Observable Method and protected OAPH field
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
public MyReactiveClass()
{
// Initialize generated _myObservablePropertyHelper
// for the generated MyObservableProperty
InitializeOAPH();
}[ObservableAsProperty(UseProtected = true)]
IObservable MyObservable() => Observable.Return("Test Value");
}
```### Usage ObservableAsPropertyHelper with partial Property and a default value
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass : ReactiveObject
{
public MyReactiveClass()
{
// The value of MyProperty will be "Default Value" until the Observable is initialized
_myPrpertyHelper = MyPropertyObservable()
.ToProperty(this, nameof(MyProperty));
}
[ObservableAsProperty(InitialValue = "Default Value")]
public string MyProperty { get; }public IObservable MyPropertyObservable() => Observable.Return("Test Value");
}
```## Usage ReactiveCommand `[ReactiveCommand]`
### Usage ReactiveCommand without parameter
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
[ReactiveCommand]
private void Execute() { }
}
```### Usage ReactiveCommand with parameter
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
[ReactiveCommand]
private void Execute(string parameter) { }
}
```### Usage ReactiveCommand with parameter and return value
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
[ReactiveCommand]
private string Execute(string parameter) => parameter;
}
```### Usage ReactiveCommand with parameter and async return value
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
[ReactiveCommand]
private async Task ExecuteAsync(string parameter) => await Task.FromResult(parameter);// Generates the following code ExecuteCommand, Note the Async suffix is removed
}
```### Usage ReactiveCommand with IObservable return value
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
[ReactiveCommand]
private IObservable Execute(string parameter) => Observable.Return(parameter);
}
```### Usage ReactiveCommand with CancellationToken
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
[ReactiveCommand]
private async Task Execute(CancellationToken token) => await Task.Delay(1000, token);
}
```### Usage ReactiveCommand with CancellationToken and parameter
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
[ReactiveCommand]
private async Task Execute(string parameter, CancellationToken token)
{
await Task.Delay(1000, token);
return parameter;
}
}
```### Usage ReactiveCommand with CanExecute
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
private IObservable _canExecute;[Reactive]
private string _myProperty1;[Reactive]
private string _myProperty2;public MyReactiveClass()
{
_canExecute = this.WhenAnyValue(x => x.MyProperty1, x => x.MyProperty2, (x, y) => !string.IsNullOrEmpty(x) && !string.IsNullOrEmpty(y));
}[ReactiveCommand(CanExecute = nameof(_canExecute))]
private void Search() { }
}
```### Usage ReactiveCommand with property Attribute pass through
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
private IObservable _canExecute;[Reactive]
private string _myProperty1;[Reactive]
private string _myProperty2;public MyReactiveClass()
{
_canExecute = this.WhenAnyValue(x => x.MyProperty1, x => x.MyProperty2, (x, y) => !string.IsNullOrEmpty(x) && !string.IsNullOrEmpty(y));
}[ReactiveCommand(CanExecute = nameof(_canExecute))]
[property: JsonIgnore]
private void Search() { }
}
```### Usage ReactiveCommand with ReactiveUI OutputScheduler
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
[ReactiveCommand(OutputScheduler = "RxApp.MainThreadScheduler")]
private void Execute() { }
}
```### Usage ReactiveCommand with custom OutputScheduler
```csharp
using ReactiveUI.SourceGenerators;public partial class MyReactiveClass
{
private IScheduler _customScheduler = new TestScheduler();[ReactiveCommand(OutputScheduler = nameof(_customScheduler))]
private void Execute() { }
}
```## Usage IViewFor `[IViewFor(nameof(ViewModelName))]`
### IViewFor usage
IViewFor is used to link a View to a ViewModel, this is used to link the ViewModel to the View in a way that ReactiveUI can use it to bind the ViewModel to the View.
The ViewModel is passed as a type to the IViewFor Attribute using generics.
The class must inherit from a UI Control from any of the following platforms and namespaces:
- Maui (Microsoft.Maui)
- WinUI (Microsoft.UI.Xaml)
- WPF (System.Windows or System.Windows.Controls)
- WinForms (System.Windows.Forms)
- Avalonia (Avalonia)
- Uno (Windows.UI.Xaml).### Usage IViewFor with ViewModel Name - Generic Types should be used with the fully qualified name, otherwise use nameof(ViewModelTypeName)
```csharp
using ReactiveUI.SourceGenerators;[IViewFor("MyReactiveGenericClass")]
public partial class MyReactiveControl : UserControl
{
public MyReactiveControl()
{
InitializeComponent();
MyReactiveClass = new MyReactiveClass();
}
}
```### Usage IViewFor with ViewModel Type
```csharp
using ReactiveUI.SourceGenerators;[IViewFor]
public partial class MyReactiveControl : UserControl
{
public MyReactiveControl()
{
InitializeComponent();
MyReactiveClass = new MyReactiveClass();
}
}
```## Platform specific Attributes
### WinForms
#### RoutedControlHost
```csharp
using ReactiveUI.SourceGenerators.WinForms;[RoutedControlHost("YourNameSpace.CustomControl")]
public partial class MyCustomRoutedControlHost;
```#### ViewModelControlHost
```csharp
using ReactiveUI.SourceGenerators.WinForms;[ViewModelControlHost("YourNameSpace.CustomControl")]
public partial class MyCustomViewModelControlHost;
```### TODO:
- Add ObservableAsProperty to generate from a IObservable method with parameters.# Credits
Portions of this code base are based on and derived from
* [PolySharp](https://github.com/Sergio0694/PolySharp) library. Thanks go to @Sergio0694
* [Microsoft MVVM Community Toolkit](https://github.com/CommunityToolkit/dotnet)