Slint.Net 0.0.1-preview02

This is a prerelease version of Slint.Net.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package Slint.Net --version 0.0.1-preview02
                    
NuGet\Install-Package Slint.Net -Version 0.0.1-preview02
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Slint.Net" Version="0.0.1-preview02" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Slint.Net" Version="0.0.1-preview02" />
                    
Directory.Packages.props
<PackageReference Include="Slint.Net" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Slint.Net --version 0.0.1-preview02
                    
#r "nuget: Slint.Net, 0.0.1-preview02"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Slint.Net@0.0.1-preview02
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Slint.Net&version=0.0.1-preview02&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=Slint.Net&version=0.0.1-preview02&prerelease
                    
Install as a Cake Tool

Slint .NET (Slint.Net)

.NET 10 bindings for Slint — a declarative UI toolkit for native user interfaces.

Status: pre-alpha / M0–M4 complete. The dynamic interpreter API, build-time code generation via Slint.Build, translations, writable models, gradients and async all work end to end. Windows is the platform exercised locally; Linux and macOS native libraries are produced by CI. Packages are not published to nuget.org yet (CI produces artifacts).

What works today

Area State
Dynamic API: Compiler, CompilationResult, ComponentDefinition, ComponentInstance ✅
Diagnostics (level / message / line / column / file) ✅
Properties: int/float/length, string, bool, color, struct, enum ✅
Exported globals: number/bool/string/color/struct/enum properties ✅
Callbacks: 0–4 arguments, optional return value ✅
Functions: 0–4 arguments, optional return value ✅
Models: read-only Model<T> over [T] properties, including nested [[T]] ✅
Models: writable ListModel<T> with change notifications ✅
Images: Image.FromPath, Image.FromSvg, Image.FromRgba8 ✅
Dynamically typed Value with conversion helpers ✅
Window: Show/Hide/Run/SetSize/Size/ScaleFactor/RequestRedraw ✅
Renderers: GPU (femtovg/OpenGL) with a software fallback ✅
Nested models and model-typed callback arguments/results ✅
Event loop: App.Run, App.Quit, App.InvokeFromEventLoop ✅
Thread-affinity checks and Windows STA checks with clear exceptions ✅
NativeAOT + single-file + trimming (Release) ✅
Build-time code generation: Slint.Build + Slint.Generator ✅
Generated models: typed properties, model callbacks/functions, global callbacks ✅
API drift detection for stale generated code ✅
Translations: @tr, managed ITranslator, TranslationDomain, default context ✅
Callback multicast + C# event in generated code (components and globals) ✅
Strongly typed struct records in generated code ✅
Gradient brushes (LinearGradient, RadialGradient) ✅
data-transfer and styled-text values ✅
Async: App.RunAsync/RunComponentAsync/InvokeAsync, SlintSynchronizationContext ✅
Manual event-loop pumping (App.ProcessEvents) for WPF/WinForms hosting ✅
data-transfer: plain text, file paths and images ✅
Linux (linux-x64) and macOS (osx-arm64) native libraries ✅ built by CI
styled-text style spans (plain text only so far) ⛔ M5
gettext / bundled translations (needs Slint 1.19) ⛔ M5
Android / iOS ⛔ M5

Type mapping

.slint C#
int, float, length, duration, angle int, float, double
string string
bool bool
color, brush (solid) Slint.Color, Slint.Brush
struct IReadOnlyDictionary<string, Slint.Value>
enum (string Type, string Variant)
[T] read: Slint.Model<T>, write: Slint.IModel (Model<T>, ListModel<T> or ModelValue)
[[T]] Slint.Model<Slint.Model<T>>, with the element reader generated
image Slint.Image + Slint.Value
callback / function Action/Func overloads, Invoke/Invoke<T>

Repository layout

Path Purpose
rust/slint-dotnet/ Native glue: a Rust cdylib exposing a flat, versioned C ABI on top of slint-interpreter
src/Slint/ Managed runtime (assembly Slint.dll, namespace Slint, package id Slint.Net)
src/Slint.Build/ MSBuild integration and the code generator (package id Slint.Build)
tools/Slint.Generator/ The generator tool that emits strongly typed C# from .slint files
src/Slint/runtimes/<rid>/native/ Native library staging area (populated by the build script, not committed)
tests/Slint.Tests/ xunit tests, including build-time generated code
tests/Slint.AotSmoke/ NativeAOT + single-file + trimming smoke app
samples/HelloWorld/ Minimal dynamic-mode sample
samples/Generated/ Strongly typed sample using Slint.Build
samples/Gallery/ Port of the official Slint widgets gallery (examples/gallery)
scripts/build-native.ps1 Builds the cdylib and stages it into the package layout
scripts/pack.ps1 Produces the Slint.Net and Slint.Build NuGet packages (optional -Version)
docs/design/ Design documents
.github/workflows/ci.yaml CI: build, test, style checks, native matrix, AOT smoke, pack
.github/workflows/release.yml Release: native matrix, tests, AOT smoke, gallery zip, NuGet packages, GitHub release

Architecture

C# application
    │  NuGet: Slint.Net (+ Slint.Build in M3)
    ▼
Slint.dll                       managed runtime, namespace Slint
    │  [LibraryImport] P/Invoke, UTF-8, Cdecl, no reflection marshalling
    ▼
slint_dotnet.dll                Rust cdylib, catch_unwind + GCHandle bridge
    │
    ▼
slint-interpreter 1.18 / i-slint-core / backends   (the same core as the official bindings)

Design rules that keep the binding NativeAOT-safe:

  • only [LibraryImport] (source-generated P/Invoke) is used, never DllImport;
  • callbacks are [UnmanagedCallersOnly] function pointers plus a GCHandle, never Marshal.GetFunctionPointerForDelegate;
  • no reflection-based marshalling, no Activator, no MakeGenericType;
  • every native resource is owned by a SafeHandle;
  • Rust panics are caught at the boundary and surfaced as SlintException;
  • managed callback exceptions never unwind through Rust frames — they are captured and re-thrown by Run().

Build-time code generation (Slint.Build)

Add the SlintFile items and the package generates a strongly typed class per exported component:

<ItemGroup>
  <PackageReference Include="Slint.Net" Version="0.1.0" />
  <PackageReference Include="Slint.Build" Version="0.1.0" PrivateAssets="all" />
  <SlintFile Include="ui/main.slint" />
</ItemGroup>
// ui/main.slint
export enum Theme { light, dark }

export global AppState {
    in-out property <int> clicks: 0;
}

export component MainWindow inherits Window {
    in-out property <int> counter: 0;
    in-out property <Theme> theme: Theme.light;
    callback clicked;
    public function doubled() -> int { return counter * 2; }
}
using AppUi;                      // the configured SlintNamespace

using var window = new MainWindow();
window.Counter++;
window.Theme = Theme.Dark;
window.Clicked += () => window.GlobalAppState.Clicks++;
Console.WriteLine(window.Doubled());
window.Run();

The generated file lives in obj/<config>/<tfm>/slint/ and contains:

  • a typed property per in/in-out property (out properties are get-only),
  • a C# event per callback, taking Action<…>/Func<…, R> delegates and supporting any number of subscribers (+=/-=),
  • a method per public function,
  • a Global<Name> class per exported global — including its callbacks, which become events registered with AddGlobalCallback,
  • a C# enum plus ToSlint/FromSlint helpers per referenced Slint enum,
  • a record plus ToValue/FromValue helpers per referenced Slint struct,
  • a class per export { Original as Alias },
  • a SlintNames class with the original .slint names,
  • an API fingerprint that is compared at load time; editing the .slint file without rebuilding throws GeneratedApiMismatchException.

Models in generated code

.slint Generated C#
in-out property <[int]> values Model<int> Values { get; set; }
in-out property <[[int]]> matrix Model<Model<int>> Matrix { get; set; }
out property <[int]> rows Model<int> Rows { get; }
callback scale([int]) -> [int] event Func<Model<int>, IModel>? Scale
callback pick([[int]], string) -> [[int]] event Func<Model<Model<int>>, string, IModel>? Pick
public function mirror(v: [int]) -> [int] Model<int> Mirror(IModel v)
export struct Box { tags: [string] } record Box { Model<string> Tags { get; init; } }

The rules behind the table:

  • Reading a model always produces a typed Model<T> view. Nested models generate the element reader for you, so Matrix[0] is a Model<int>.
  • Writing a model (property setters, function parameters, callback results) takes IModel, so a writable ListModel<T>, a read-only Model<T> or a non-generic ModelValue can all be passed.
  • Model property getters are typed, so their setters accept the same view; ListModel<T> has an implicit conversion to Model<T> (backed by AsReadOnly()), which keeps window.Values = listModel; working.
  • StandardListViewItem and other builtin Slint structs have no declared name, so they surface as IReadOnlyDictionary<string, Value> (the text field of a table cell is cell["text"]).
using var window = new MainWindow();

// Set a model from C#; Slint keeps its own reference.
using var values = new ListModel<int>([1, 2, 3]);
window.Values = values;

// A model-of-models callback: the argument and result are typed views.
window.Pick += (source, filter) =>
{
    var result = new ListModel<ListModel<int>>();
    foreach (var row in source)
    {
        result.Add(new ListModel<int>(row));
    }

    return result;
};

MSBuild properties: SlintNamespace, SlintGeneratorPath, SlintGeneratedDir, SlintGeneratorOptions (extra generator arguments such as --style fluent).

The .slint files are copied next to the application, because the generated code loads them at run time.

Producing the packages

./scripts/pack.ps1 -Configuration Release   # writes artifacts/Slint.Net.*.nupkg and artifacts/Slint.Build.*.nupkg

Pass -Version 1.2.3 to override the version baked into the projects, and -SkipNative when the native libraries under src/Slint/runtimes/<rid>/native/ were staged by an earlier job. The Slint.Build package carries the code generator (tools/net10.0/) together with the native library of every staged RID, so it works on any of the supported build hosts.

Releasing

.github/workflows/release.yml runs when a v* tag is pushed (or on demand via workflow_dispatch with a tag input). It:

  1. builds the native library for win-x64, win-arm64, linux-x64 and osx-arm64 on matching runners;
  2. runs the managed tests and the NativeAOT smoke test;
  3. publishes the gallery sample as a NativeAOT, single-file, trimmed win-x64 build, runs its --smoke check and zips it;
  4. packs Slint.Net and Slint.Build (the latter with the generator) and zips the generator on its own;
  5. creates a source archive and a GitHub release with all of the above attached.

Release assets carry no debug symbols: the gallery zip is published with StripSymbols=true and its .pdb files are removed, and pack.ps1 strips the generator's .pdb files before packing so neither Slint.Build nor the standalone generator zip ships them.

git tag v0.1.0
git push origin v0.1.0

A hyphen in the tag (for example v0.2.0-pre.1) marks the GitHub release as a pre-release.

Publishing to nuget.org is opt-in: the last two steps run only when the NUGET_USER repository secret holds the nuget.org profile name and a trusted publishing policy exists for this repository and the release.yml workflow. Without it the release still produces the packages as release assets.

Translations

Slint's @tr(...) strings are translated through any implementation of Slint.ITranslator, which is the .NET counterpart of the Python binding's gettext object:

App.SetTranslator(new MyTranslator());   // App.SetTranslator(null) removes it

sealed class MyTranslator : ITranslator
{
    public string? Translate(string text, string? context) => resources.GetString(text);
    public string? TranslatePlural(ulong n, string singular, string plural, string? context)
        => n == 1 ? resources.GetString(singular) : resources.GetString(plural);
}

Returning null keeps the original text. This works with .resx, IStringLocalizer, a database, or anything else.

Compile-time settings on Compiler:

  • TranslationDomain — the gettext domain;
  • DefaultTranslationContext — ComponentName (default) or None, matching slint-tr-extractor;
  • BundledTranslationsPath — not available with Slint 1.18.x because slint-interpreter only publishes the bundle-translations feature from 1.19 on. Setting it throws a SlintException explaining this, and App.SelectBundledTranslation is wired up for when the dependency is upgraded.

Async

The event loop can run on a dedicated STA thread, and await resumes on the UI thread thanks to an installed SynchronizationContext:

// Runs the loop on a UI thread and creates the window there (instances are
// thread-affine, so the component is built by the factory).
var ui = App.RunComponentAsync(() => new MainWindow());

// Marshal work to the UI thread and await it.
var count = await App.InvokeAsync(() => window.Counter);
await App.InvokeAsync(() => window.Counter = count + 1);

App.Quit();
await ui;

Inside a callback, await continues on the UI thread:

window.Clicked += async () =>
{
    var data = await httpClient.GetStringAsync(url);   // runs in the background
    window.Status = data;                              // back on the UI thread
};

An async callback handler returning a Task is observed in the background; its exceptions surface through App.Run/RunComponentAsync.

Hosting Slint in another UI framework

App.Run takes over the thread, which does not fit WPF, WinForms or a game loop. Those hosts can instead pump Slint themselves with App.ProcessEvents:

[STAThread]
static void Main()
{
    var ui = new MainWindow();
    App.SetQuitOnLastWindowClosed(false);   // the host decides when to stop
    ui.Show();

    // e.g. hook ComponentDispatcher.ThreadIdle, a DispatcherTimer, or the game loop
    while (running)
    {
        if (App.ProcessEvents(TimeSpan.FromMilliseconds(16)) == ProcessEventsResult.Exited)
        {
            break;
        }
    }

    ui.Hide();
}

ProcessEvents accepts null (block until an event arrives) or a timeout.

Platforms

RID Status
win-x64, win-arm64 Built and tested locally / in CI
linux-x64, osx-arm64 Built by CI (native-unix job); not exercised by the Windows test suite

Adding a platform only requires staging its native library under src/Slint/runtimes/<rid>/native/; the NuGet package picks up every staged RID automatically, and Slint.Build bundles one native library per host RID so the generator works whichever platform you build on.

Samples

Sample Shows
samples/HelloWorld The smallest dynamic-mode app: compile .slint, wire a callback, Run().
samples/Generated Slint.Build code generation: typed properties, events, enums, globals.
samples/Gallery Port of the official widgets gallery, built with Slint.Build code generation.

The .slint files, images and gettext catalogues are copied verbatim from the Slint repository; main.rs is replaced by Program.cs, and slint::init_translations! by a managed ITranslator that reads the .mo catalogues:

dotnet run --project samples/Gallery                 # uses the OS UI language
dotnet run --project samples/Gallery -- --locale fr  # forces a catalogue
dotnet run --project samples/Gallery -- --smoke      # headless check

The gallery is built with Slint.Build, so export component App becomes Gallery.App and export global TableViewPageAdapter becomes Gallery.GlobalTableViewPageAdapter. Program.cs then reads like main.rs:

using var app = new App();

using var table = CreateTableModel(rows: 100, columns: 4);
app.GlobalTableViewPageAdapter.RowData = table;

// main.rs's `filter_sort_model`.
app.GlobalTableViewPageAdapter.FilterSortModel += FilterSortModel;

app.Run();

Notes on the port:

  • The table page's filter_sort_model callback is wired, including its model-of-models argument and result — Program.cs uses the generated typed event, so filtering and sorting the table behave like the Rust example.
  • App (the generated component) and Slint.App (the event loop) share a name; inside the sample's namespace the component wins, and the event loop stays fully qualified (Slint.App.SetTranslator, Slint.App.BuildFeatures).
  • MoTranslator is sample code that parses .mo files; a real application would more likely implement ITranslator over .resx/IStringLocalizer.

Nested models

A .slint model whose elements are themselves models — [[T]] — maps to a Model<Model<T>> in generated code. Model<T> needs the element type at compile time, so the generator also emits the reader that turns one row value into the inner model:

// Generated for `in-out property <[[int]]> matrix`
public Model<Model<int>> Matrix
{
    get
    {
        using var value = Instance.GetValue("matrix");
        return value.AsModel<Model<int>>(static element0 => element0.AsModel<int>());
    }
    set => Instance.SetValue("matrix", value.ToValue());
}

When the element type is not known at compile time (hand-written code, or a [[T]] whose T is opaque), the non-generic ModelValue does the same job and the element reader can be passed explicitly:

using var source = someValue.AsModelValue();
using var rows = source.AsModel<Model<int>>(static element => element.AsModel<int>());

Models are passed in both directions:

  • to Slint — ListModel<T>, Model<T> and ModelValue all implement IModel, so they can be assigned to a model property, passed to a function or returned from a callback;
  • from Slint — property getters, callback arguments and function results are typed Model<T> views (with the reader supplied for nested models).

Known limitations

  • export component X inherits Window, component X + export { X }, export { X as Y }, export enum, export struct and export global are all supported and covered by tests.
  • Upstream bug: exporting the same component twice (export { D } together with export { D as DAlias }) makes i-slint-compiler 1.18.1 panic in passes/generate_item_indices.rs. The binding turns the panic into a SlintException instead of crashing the process, and the generator reports it as a build error.
  • Callbacks are C# events with fan-out in managed code: Slint has a single handler slot per callback, so ComponentInstance.AddCallback/RemoveCallback multiplex subscribers and generated code exposes +=/-=.
  • Models: Model<T> is a read-only view of a Slint model; ListModel<T> is a writable model owned by C# that notifies Slint on mutation. A ListModel<T> that is never disposed is never collected — the payload registry keeps a strong reference so Slint can call back into it — so dispose it once Slint no longer needs it (the gallery does this after assigning the table).
  • Generated structs are records; structs that Slint reports without a name (anonymous literals) stay IReadOnlyDictionary<string, Slint.Value>.
  • data-transfer payloads expose plain text, file paths and an image; styled-text values expose their plain-text form (style spans are not surfaced yet).

Requirements

  • Rust 1.85+ (edition 2024)
  • .NET SDK 10 (global.json pins 10.0.401)
  • Windows x64 (arm64 is built in CI but not exercised by the local scripts)

Build and test

# 1. Build the native library and stage it into src/Slint/runtimes/<rid>/native/
./scripts/build-native.ps1 -Configuration Debug

# 2. Build and test the managed side
dotnet test tests/Slint.Tests

# 3. Run the sample (opens a window)
dotnet run --project samples/HelloWorld

Useful options:

./scripts/build-native.ps1 -Configuration Release                  # optimized native library
./scripts/build-native.ps1 -Rid win-arm64 -RustTarget aarch64-pc-windows-msvc
./scripts/build-native.ps1 -Features renderer-femtovg              # opt into another renderer

The default feature set is backend-winit + renderer-femtovg + renderer-software + accessibility. Slint picks the first renderer that can initialise: femtovg (OpenGL, GPU) when a GL context is available, and the software renderer otherwise. Force one with the SLINT_BACKEND environment variable:

$env:SLINT_BACKEND = "winit-femtovg"   # GPU
$env:SLINT_BACKEND = "winit-software"  # CPU

renderer-skia is wired up as a feature but not enabled by default.

NativeAOT

The single-file + trimming + NativeAOT trio is enabled for Configuration=Release only (Debug stays a normal JIT build for fast iteration):

dotnet publish tests/Slint.AotSmoke -c Release -r win-x64
./tests/Slint.AotSmoke/bin/Release/net10.0/win-x64/publish/Slint.AotSmoke.exe

The publish is required to be warning-free; TreatWarningsAsErrors is on, so any trimming/AOT warning fails the build.

Usage

using Slint;

using var compiler = new Compiler();
using var result = compiler.BuildFromPath("ui/main.slint");

foreach (var diagnostic in result.Diagnostics)
{
    Console.Error.WriteLine(diagnostic);
}

using var definition = result.RequireComponent("MainWindow");
using var ui = definition.Create();

ui.SetCallback("clicked", () =>
{
    ui.SetProperty("counter", ui.GetProperty<int>("counter") + 1);
});

ui.Run();

ComponentDefinition exposes the parsed public API so you can inspect it without generated code:

foreach (var (name, type) in definition.Properties) { /* ... */ }
foreach (var callback in definition.Callbacks) { /* ... */ }
foreach (var global in definition.Globals)
{
    _ = definition.GlobalProperties(global);
}

Callbacks with arguments and return values, colors, structs, enums and models:

ui.SetProperty("fill", new Color(0x33, 0x66, 0x99));
ui.SetCallback<int, int, int>("compute", (a, b) => a * b);
var result = ui.Invoke<int>("compute", 3, 4);

using var numbers = ui.GetValue("numbers");
using var model = numbers.AsModel<int>();
Console.WriteLine(model.Count);

using var image = Image.FromRgba8(2, 2, rgbaPixels);
ui.SetValue("icon", image);

Windows: the entry point must be [STAThread]

Slint's windowing backend initialises COM with OleInitialize, which requires a single-threaded apartment. The .NET entry thread defaults to MTA, so Show()/Run() fail with RPC_E_CHANGED_MODE unless the entry point is annotated:

[STAThread]
private static void Main()
{
    // ... build the component, then ui.Run();
}

The binding checks this up front and throws an InvalidOperationException that mentions [STAThread], instead of surfacing the native panic. Top-level statements cannot carry the attribute, so applications that show a window need an explicit Main (see samples/HelloWorld).

Window geometry (SetSize, Size, ScaleFactor, RequestRedraw) does not require the event loop and therefore works without STA.

License

This binding is licensed under the MIT License, see LICENSE.

The native library links against Slint, which is triple-licensed (GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0). Distributing an application that uses this binding is subject to Slint's license terms.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.0.1-preview03 90 9/24/2026
0.0.1-preview02 81 9/23/2026
0.0.1-preview01 77 9/23/2026