### Window Control Setup in CSharpMarkup
Source: https://github.com/aprillz/mewui/blob/main/docs/CSharpMarkup.md
Demonstrates the basic setup for a Window control, including setting its title, size, content, and event handlers for loading and closing.
```csharp
new Window()
.Title("My App")
.Resizable(800, 600)
.Content(...)
.OnLoaded(() => ...)
.OnClosed(() => ...)
```
--------------------------------
### Minimal Application Setup and Run
Source: https://github.com/aprillz/mewui/blob/main/docs/ApplicationLifecycle.md
Demonstrates the minimal setup required to create and run a MewUI application with a basic window. This is typically called after all necessary platform and backend configurations are complete.
```csharp
var window = new Window()
.Title("Hello")
.Content(new TextBlock().Text("Hello, MewUI"));
Application.Run(window);
```
--------------------------------
### Full Hot Reload Example
Source: https://github.com/aprillz/mewui/blob/main/docs/HotReload.md
A complete example demonstrating how to enable Hot Reload and register a build callback for a window. The DateTime.Now will update after a code change and Hot Reload.
```csharp
#if DEBUG
[assembly: System.Reflection.Metadata.MetadataUpdateHandler(
typeof(Aprillz.MewUI.HotReload.MewUiMetadataUpdateHandler))]
#endif
using Aprillz.MewUI;
using Aprillz.MewUI.Markup;
using Aprillz.MewUI.Controls;
// 1) Register a build callback (DateTime updates after code change + Hot Reload)
var window = new Window()
.OnBuild(w => w
.Title("Hot Reload Demo")
.Content(new StackPanel()
.Spacing(8)
.Children(
new TextBlock().Text($"Now: {DateTime.Now}"),
new Button().Content("Click")
)));
// 2) Select platform/backend and run
Application.Create()
.UseWin32()
.UseDirect2D()
.Run(window);
```
--------------------------------
### State-Driven Border and Pixel Snapping Example
Source: https://github.com/aprillz/mewui/blob/main/docs/CustomControls.md
Demonstrates how to use utility methods to determine DPI scale, get the visual state, pick an accent border, and snap bounds to pixels for drawing. Use this for rendering custom control borders that adapt to different states and DPI settings.
```csharp
var dpiScale = GetDpi() / 96.0;
var state = GetVisualState(isPressed: isPressed, isActive: isActive);
var border = PickAccentBorder(Theme, BorderBrush, state, hoverMix: 0.6);
var bounds = LayoutRounding.SnapBoundsRectToPixels(Bounds, dpiScale);
DrawBackgroundAndBorder(context, bounds, Background, border, cornerRadiusDip: 0);
```
--------------------------------
### MewUI C# Markup Example
Source: https://github.com/aprillz/mewui/blob/main/README.md
Demonstrates building a simple UI with a window, label, and button using MewUI's fluent C# markup. This example shows how to set window properties and handle button clicks.
```csharp
var window = new Window()
.Title("Hello MewUI")
.Size(520, 360)
.Padding(12)
.Content(
new StackPanel()
.Spacing(8)
.Children(
new Label()
.Text("Hello, Aprillz.MewUI")
.FontSize(18)
.Bold(),
new Button()
.Content("Quit")
.OnClick(() => Application.Quit())
)
);
Application.Run(window);
```
--------------------------------
### Manage Multiple Windows
Source: https://github.com/aprillz/mewui/blob/main/docs/ApplicationLifecycle.md
This example demonstrates how to create and manage multiple windows. The 'Tools' window is shown when the 'Main' window is loaded.
```csharp
var main = new Window()
.Title("Main")
.Content(new TextBlock().Text("Main window"));
var tools = new Window()
.Title("Tools")
.Content(new TextBlock().Text("Tools window"));
main.OnLoaded(() => tools.Show());
Application.Run(main);
```
--------------------------------
### Add WebView2 Integration
Source: https://github.com/aprillz/mewui/blob/main/docs/Installation.md
Install the WebView2 integration package for Windows if needed.
```bash
dotnet add package Aprillz.MewUI.Win32.WebView2
```
--------------------------------
### Install Windows Metapackage
Source: https://github.com/aprillz/mewui/blob/main/docs/Installation.md
Use this command to add the Windows metapackage to your project.
```bash
dotnet add package Aprillz.MewUI.Windows
```
--------------------------------
### CheckBox Control Setup in CSharpMarkup
Source: https://github.com/aprillz/mewui/blob/main/docs/CSharpMarkup.md
Illustrates the setup for a CheckBox, including its label text and binding its checked state to an observable value.
```csharp
new CheckBox()
.Text("Enable feature")
.BindIsChecked(vm.IsEnabled)
```
--------------------------------
### Install Cross-Platform Metapackage
Source: https://github.com/aprillz/mewui/blob/main/docs/Installation.md
Use this command to add the cross-platform metapackage to your project.
```bash
dotnet add package Aprillz.MewUI
```
--------------------------------
### Label Control Setup in CSharpMarkup
Source: https://github.com/aprillz/mewui/blob/main/docs/CSharpMarkup.md
Shows how to create and configure a Label control with text content, font styling, and size.
```csharp
new Label()
.Text("Hello World")
.Bold()
.FontSize(16)
```
--------------------------------
### Initialize and Use WebView2 Control
Source: https://github.com/aprillz/mewui/blob/main/src/MewUI.Win32.WebView2/README.md
Demonstrates basic initialization of the WebView2 control, setting its source, executing JavaScript, and handling web messages. Ensure the WebView2 Runtime is installed.
```csharp
var webView = new WebView2();
webView.Source = new Uri("https://example.com");
// JavaScript execution
string result = await webView.ExecuteScriptAsync("document.title");
// Web message handling
webView.WebMessageReceived += (sender, e) => {
Console.WriteLine($"Message: {e.WebMessageAsJson}");
};
```
--------------------------------
### TextBox Control Setup in CSharpMarkup
Source: https://github.com/aprillz/mewui/blob/main/docs/CSharpMarkup.md
Demonstrates how to set up a TextBox with placeholder text and bind its content to an observable value.
```csharp
new TextBox()
.Placeholder("Enter name...")
.BindText(vm.Name)
```
--------------------------------
### Install Individual Packages
Source: https://github.com/aprillz/mewui/blob/main/docs/Installation.md
Reference specific MewUI packages in your project file when not using metapackages.
```xml
```
--------------------------------
### Main Window Setup and Events
Source: https://context7.com/aprillz/mewui/llms.txt
Configure the main window's title, size, padding, content, and various event handlers like `OnLoaded`, `OnClosed`, `OnSizeChanged`, `OnDpiChanged`, `OnThemeChanged`, and `OnFirstFrameRendered`. Native resources are created at `Show()` or `Application.Run()` time.
```csharp
using Aprillz.MewUI;
using Aprillz.MewUI.Controls;
// Main window — shown by Application.Run
var main = new Window()
.Title("Main Window")
.Resizable(800, 600) // resizable with initial size
.Padding(12)
.Content(new Label().Text("Main"))
.OnLoaded(() => Console.WriteLine("Window loaded"))
.OnClosed(() => Application.Quit())
.OnSizeChanged(size => Console.WriteLine($
```
```csharp
Size: {size})
.OnDpiChanged((oldDpi, newDpi) => Console.WriteLine($"DPI: {newDpi}"))
.OnThemeChanged((old, cur) => Console.WriteLine($"Theme: {cur.Variant}"))
.OnFirstFrameRendered(() => Console.WriteLine("First frame!"));
// Tool window launched from Loaded
main.OnLoaded(() =>
{
var tools = new Window()
.Title("Tools")
.Fixed(300, 200) // fixed size
.Content(new Label().Text("Tools"));
tools.Show();
});
// Modal dialog
var dialog = new Window()
.Title("Confirm")
.FitContentSize(400, 300) // size adapts to content
.Content(new Label().Text("Are you sure?"));
// await dialog.ShowDialogAsync(owner: main);
// Key preview at the window level
main.OnPreviewKeyDown(e =>
{
if (e.Key == Key.Escape) { Application.Quit(); e.Handled = true; }
});
Application.Run(main);
```
--------------------------------
### Button Control Setup in CSharpMarkup
Source: https://github.com/aprillz/mewui/blob/main/docs/CSharpMarkup.md
Illustrates the configuration of a Button control, including its content, click event handler, and conditional click logic.
```csharp
new Button()
.Content("Click Me")
.OnCanClick(() => isFormValid)
.OnClick(() => Submit())
```
--------------------------------
### Add Aprillz.MewUI Package
Source: https://github.com/aprillz/mewui/blob/main/NUGET_README.md
Install the Aprillz.MewUI metapackage or platform-specific packages using the .NET CLI.
```sh
# Cross-platform (all-in-one)
dotnet add package Aprillz.MewUI
# Or platform-specific
dotnet add package Aprillz.MewUI.Windows
dotnet add package Aprillz.MewUI.Linux
dotnet add package Aprillz.MewUI.MacOS
```
--------------------------------
### Add MewUI NuGet Packages
Source: https://context7.com/aprillz/mewui/llms.txt
Use `dotnet add package` to install the all-in-one metapackage or platform-specific ones. Individual packages allow for fine-grained composition.
```bash
# Cross-platform (all platforms + all backends)
dotnet add package Aprillz.MewUI
# Windows only
dotnet add package Aprillz.MewUI.Windows
# Linux only
dotnet add package Aprillz.MewUI.Linux
# macOS only
dotnet add package Aprillz.MewUI.MacOS
# Individual packages (fine-grained composition)
# dotnet add package Aprillz.MewUI.Core
# dotnet add package Aprillz.MewUI.Platform.Win32
# dotnet add package Aprillz.MewUI.Backend.Direct2D
# Additional optional packages
dotnet add package Aprillz.MewUI.Svg
dotnet add package Aprillz.MewUI.Win32.WebView2
```
```xml
```
--------------------------------
### Create and Configure a TabControl
Source: https://github.com/aprillz/mewui/blob/main/docs/CSharpMarkup.md
Instantiate a TabControl and define its tab items, each with a header and content. This example shows how to define multiple tabs programmatically.
```csharp
new TabControl()
.TabItems(
new TabItem().Header("Home").Content(...),
new TabItem().Header("Settings").Content(...)
)
```
--------------------------------
### MultiLineTextBox Control Setup in CSharpMarkup
Source: https://github.com/aprillz/mewui/blob/main/docs/CSharpMarkup.md
Shows the configuration for a MultiLineTextBox, including placeholder, word wrap, height, and text binding.
```csharp
new MultiLineTextBox()
.Placeholder("Enter notes...")
.Wrap(true)
.Height(100)
```
--------------------------------
### Configure Render Loop Settings
Source: https://context7.com/aprillz/mewui/llms.txt
After `Application.Run` starts, configure render loop mode, target FPS, and VSync via `Application.Current.RenderLoopSettings`. Set `TargetFps` to 0 for unlimited frames.
```csharp
// After Application.Run starts, configure via Application.Current
Application.Current.RenderLoopSettings.SetContinuous(true); // continuous vs. on-request
Application.Current.RenderLoopSettings.VSyncEnabled = false;
Application.Current.RenderLoopSettings.TargetFps = 60; // 0 = unlimited
```
--------------------------------
### UI Binding Example for LoginViewModel
Source: https://github.com/aprillz/mewui/blob/main/docs/Binding.md
Demonstrates how to bind UI elements like TextBox, CheckBox, Label, and Button to the properties of a LoginViewModel. Includes text binding, checked binding, and click event handling.
```csharp
var vm = new LoginViewModel();
new StackPanel()
.Vertical()
.Spacing(8)
.Children(
new TextBox()
.Placeholder("Username")
.BindText(vm.Username),
new TextBox()
.Placeholder("Password")
.BindText(vm.Password),
new CheckBox()
.Content("Remember me")
.BindIsChecked(vm.RememberMe),
new Label()
.Foreground(Color.FromRgb(200, 60, 60))
.BindText(vm.ErrorMessage),
new Button()
.Content("Login")
.OnCanClick(() => !vm.IsLoading.Value)
.OnClick(() => vm.Login())
)
```
--------------------------------
### Add SVG Support
Source: https://github.com/aprillz/mewui/blob/main/docs/Installation.md
Install the SVG package separately if you need SVG parsing and rendering capabilities.
```bash
dotnet add package Aprillz.MewUI.Svg
```
--------------------------------
### TemplateContext Registration and Get
Source: https://github.com/aprillz/mewui/blob/main/docs/ItemsAndTemplates.md
Demonstrates registering named UI elements within a TemplateContext for later retrieval. This is crucial for efficient access to elements during the bind phase.
```csharp
public sealed class TemplateContext : IDisposable
{
public void Register(string name, T element) where T : UIElement;
public T Get(string name) where T : UIElement;
// Internal lifecycle management (not part of the public contract).
}
```
```csharp
ctx.Get("Name").Text = item.Name;
```
--------------------------------
### Create a Custom Control in C#
Source: https://context7.com/aprillz/mewui/llms.txt
Derive from Control and override MeasureContent and OnRender. Use DIP for layout and pixel-snap for rendering. Example shows a ColorSwatch control.
```csharp
using Aprillz.MewUI.Controls;
using Aprillz.MewUI.Rendering;
// Minimal custom control example derived from Control
public sealed class ColorSwatch : Control
{
private Color _color = Color.Red;
public Color SwatchColor
{
get => _color;
set
{
if (_color == value) return;
_color = value;
InvalidateVisual(); // layout unchanged; only repaint
}
}
// Theme default sizing
protected override double DefaultMinHeight => Theme.Metrics.BaseControlHeight;
protected override Color DefaultBorderBrush => Theme.Palette.ControlBorder;
// Measure in DIP — no pixel math here
protected override Size MeasureContent(Size available)
=> new Size(Width, Theme.Metrics.BaseControlHeight);
// Render — pixel-snap, then draw
protected override void OnRender(IGraphicsContext context)
{
var dpiScale = GetDpi() / 96.0;
var bounds = LayoutRounding.SnapBoundsRectToPixels(Bounds, dpiScale);
double radius = Theme.Metrics.ControlCornerRadius;
// Background fill
DrawBackgroundAndBorder(context, bounds, _color, BorderBrush, radius);
// Centered text label
context.DrawText(
$("#{_color.R:X2}{_color.G:X2}{_color.B:X2}"),
bounds,
GetFont(),
Theme.Palette.WindowText,
TextAlignment.Center,
TextAlignment.Center,
TextWrapping.NoWrap);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (!IsEffectivelyEnabled || e.Button != MouseButton.Left) return;
Focus();
// Toggle example
SwatchColor = SwatchColor == Color.Red ? Color.Blue : Color.Red;
e.Handled = true;
}
protected override void OnThemeChanged(Theme oldTheme, Theme newTheme)
{
base.OnThemeChanged(oldTheme, newTheme);
InvalidateVisual();
}
}
// Usage
new ColorSwatch()
.Width(120)
.Height(36)
.Margin(4)
```
--------------------------------
### Button Style with Transitions
Source: https://github.com/aprillz/mewui/blob/main/docs/Styling.md
Adds transitions for background, border brush, and foreground properties to animate changes between states. This example assumes setters and triggers are defined elsewhere.
```csharp
var style = new Style(typeof(Button))
{
Transitions =
[
Transition.Create(Control.BackgroundProperty),
Transition.Create(Control.BorderBrushProperty),
Transition.Create(Control.ForegroundProperty),
],
Setters = [...],
Triggers = [...],
};
```
--------------------------------
### MewUI Theme Configuration (Pre-run)
Source: https://context7.com/aprillz/mewui/llms.txt
Sets default theme properties like `ThemeVariant`, `Accent`, `ThemeSeed` (for light and dark modes), and `ThemeMetrics` before the application starts. This configures the global appearance of the UI.
```csharp
using Aprillz.MewUI;
// --- Pre-run configuration ---
ThemeManager.Default = ThemeVariant.System; // System | Light | Dark
ThemeManager.DefaultAccent = Accent.Blue; // built-in preset
ThemeManager.DefaultLightSeed = ThemeSeed.DefaultLight with
{
WindowText = Color.FromRgb(20, 20, 20),
ControlBackground = Color.FromRgb(245, 245, 245),
};
ThemeManager.DefaultDarkSeed = ThemeSeed.DefaultDark with
{
WindowText = Color.FromRgb(240, 240, 240),
};
ThemeManager.DefaultMetrics = ThemeMetrics.Default with
{
ControlCornerRadius = 6,
FontSize = 13,
FontFamily = "Noto Sans",
};
```
--------------------------------
### MewUI Data Binding: ViewModel Pattern Implementation
Source: https://context7.com/aprillz/mewui/llms.txt
Shows a practical implementation of the ViewModel pattern using ObservableValue for managing UI state and logic. This example includes properties for username, password, loading status, and error messages, along with a login method. Requires importing Aprillz.MewUI.Binding.
```csharp
using Aprillz.MewUI.Binding;
using Aprillz.MewUI.Controls;
// --- ViewModel pattern ---
class LoginViewModel
{
public ObservableValue Username { get; } = new("");
public ObservableValue Password { get; } = new("");
public ObservableValue IsLoading { get; } = new(false);
public ObservableValue Error { get; } = new("");
public void Login()
{
if (string.IsNullOrEmpty(Username.Value)) { Error.Value = "Username required"; return; }
IsLoading.Value = true;
// ... async login logic ...
}
}
var vm = new LoginViewModel();
var form = new StackPanel().Vertical().Spacing(8).Children(
new TextBox().Placeholder("Username").BindText(vm.Username),
new TextBox().Placeholder("Password").BindText(vm.Password),
new Label().Foreground(Color.FromRgb(200, 60, 60)).BindText(vm.Error),
new Button()
.Content("Login")
.OnCanClick(() => !vm.IsLoading.Value)
.OnClick(() => vm.Login()));
```
--------------------------------
### Create a Basic Window with Controls
Source: https://github.com/aprillz/mewui/blob/main/NUGET_README.md
Demonstrates creating a simple window with a label and a button using MewUI's fluent C# markup. Ensure you have the necessary using directives.
```csharp
using Aprillz.MewUI;
using Aprillz.MewUI.Controls;
var window = new Window()
.Title("Hello MewUI")
.Size(520, 360)
.Padding(12)
.Content(
new StackPanel()
.Spacing(8)
.Children(
new Label().Text("Hello, Aprillz.MewUI").FontSize(18).Bold(),
new Button().Content("Quit").OnClick(() => Application.Quit())
)
);
Application.Run(window);
```
--------------------------------
### Create and Configure an Image
Source: https://github.com/aprillz/mewui/blob/main/docs/CSharpMarkup.md
Instantiate an Image, specify the source file, set its size, and define the stretching mode.
```csharp
new Image()
.SourceFile("logo.png")
.Size(64, 64)
.StretchMode(ImageStretch.Uniform)
```
--------------------------------
### Create and Configure a ComboBox
Source: https://github.com/aprillz/mewui/blob/main/docs/CSharpMarkup.md
Instantiate a ComboBox, provide a list of items, set a placeholder text, and specify the initially selected index.
```csharp
new ComboBox()
.Items("Small", "Medium", "Large")
.Placeholder("Select size...")
.SelectedIndex(1)
```
--------------------------------
### Publish with Publish Profile (CLI)
Source: https://github.com/aprillz/mewui/blob/main/docs/Installation.md
Execute the publish command using a pre-configured publish profile.
```bash
dotnet publish -p:PublishProfile=Win-Direct2D
```
--------------------------------
### Publish with GDI Backend (CLI)
Source: https://github.com/aprillz/mewui/blob/main/docs/Installation.md
Publish your Windows application, keeping only the lightweight GDI rendering backend.
```bash
dotnet publish -r win-x64 -p:MewUIBackend=Gdi
```
--------------------------------
### DelegateTemplate with TemplateContext
Source: https://github.com/aprillz/mewui/blob/main/docs/ItemsAndTemplates.md
Standard implementation of IDataTemplate. This example shows how to use TemplateContext for named element registration and lookup during the build and bind phases.
```csharp
var template = new DelegateTemplate(
build: ctx =>
{
// Default-template shape: a single TextBlock.
// Use TemplateContext when you want named access and reuse.
return new TextBlock().Register(ctx, "Text");
},
bind: (view, item, index, ctx) =>
{
ctx.Get("Text").Text = item.Name;
});
```
--------------------------------
### Define Type-Based Rules
Source: https://github.com/aprillz/mewui/blob/main/docs/Styling.md
Automatically apply a style to all controls of a specific type within a StyleSheet. This example applies a flatButtonStyle to all Buttons within a toolbar.
```csharp
var toolbar = new StackPanel().Horizontal().Spacing(4);
toolbar.StyleSheet = new StyleSheet();
toolbar.StyleSheet.Define