BorrowedTorch.UI
2.6.1
Prefix Reserved
dotnet add package BorrowedTorch.UI --version 2.6.1
NuGet\Install-Package BorrowedTorch.UI -Version 2.6.1
<PackageReference Include="BorrowedTorch.UI" Version="2.6.1" />
<PackageVersion Include="BorrowedTorch.UI" Version="2.6.1" />
<PackageReference Include="BorrowedTorch.UI" />
paket add BorrowedTorch.UI --version 2.6.1
#r "nuget: BorrowedTorch.UI, 2.6.1"
#:package BorrowedTorch.UI@2.6.1
#addin nuget:?package=BorrowedTorch.UI&version=2.6.1
#tool nuget:?package=BorrowedTorch.UI&version=2.6.1
BorrowedTorch.UI
UI framework for XNA / MonoGame projects, namespace BorrowedTorch.UI.
Elements are laid out WPF-style (margins, alignments, desired / min / max sizes, fit-to-content),
every element property is a dependency property that can be set by hand, by a style, or bound to a view model,
and the whole tree is drawn with a single SpriteBatch.
Requirements
- .NET 10 SDK (the project targets
net10.0-windows10.0.19041.0, C# 14fieldkeyword is used) - MonoGame 3.8.1.303 or newer - DesktopGL, WindowsDX or BorrowedTorch's compute fork: the game brings its own platform package. The library is compiled against MonoGame 3.8.1.303, and .NET loads it with that version or a newer one. The tests and the demo run on DesktopGL 3.8.4
- Packages:
BorrowedTorch.Animations(the animations' time line and blends),BorrowedTorch.MonoInput,BorrowedTorch.ShapingFunctions,FontStashSharp.MonoGame, andBorrowedTorch.UIDPGenerator(build-time only, see Dependency properties)
Project state
Every element is usable. Nothing depends on shaders built for one graphics platform, so the library works the same on DesktopGL (OpenGL) and WindowsDX.
Getting started
Create the framework once the GraphicsDevice exists and give it the game window, then call Update / Draw every
frame. The UI takes the typed text and the keys from the window, and follows the size of the back buffer by itself: at
the start of every Update it compares the back buffer with the size it saw last, and lays itself out again when the
window was resized or the game changed the back buffer. Disposing the UI unsubscribes from the window.
The game owns the input polling: call KeyboardManager.Update() and MouseManager.Update() of BorrowedTorch.MonoInput
once per frame before Update, the UI reads the same managers (polling them twice in a frame would lose the presses).
The framework keeps its state in statics, so one BorrowedTorchUI exists at a time: creating a second one throws,
dispose the first one before.
using BorrowedTorch.MonoInput.Inputs.Keyboard;
using BorrowedTorch.MonoInput.Inputs.Mouse;
using BorrowedTorch.UI;
using BorrowedTorch.UI.Elements;
public class MyGame : Game
{
private readonly GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
private BorrowedTorchUI _ui;
public MyGame()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
Window.AllowUserResizing = true;
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
_ui = new BorrowedTorchUI(GraphicsDevice, Content, _spriteBatch, Window);
_ui.ExceptionHandler = e => Console.Error.WriteLine(e);
_ui.AddElementToRoot(new Button("okButton")
{
Text = "OK",
DesiredWidth = 120,
DesiredHeight = 40,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
});
_ui.GetElementByName<Button>("okButton").OnClick += (sender, e) => Console.WriteLine("clicked");
}
protected override void Update(GameTime gameTime)
{
KeyboardManager.Update();
MouseManager.Update();
_ui.Update(gameTime);
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
_ui.Draw();
base.Draw(gameTime);
}
protected override void UnloadContent()
{
_ui.Dispose();
}
}
Two cases need more than the window:
- A UI drawn into a render target of its own size. Set
FollowsBackBufferto false and give the size withApplyGameWindowSize(width, height), in device pixels. With following on, a size given by hand stays until the back buffer changes. When that target is shown somewhere else than where the mouse reads it, scaled or moved (a tool previewing the UI at a game's resolution inside its viewport, say), setShownAtto the rectangle it is shown in, in the window's device pixels: the mouse is read through it, mapped onto the UI's screen. Null (the default) reads the mouse as it is.MousePositiongives the mouse as the elements read it, in logical units, for a tool working over the UI. - A UI hosted outside of a game window, for example in a WPF editor or a test. Pass an
ITextInputEventsof your own instead of the window. The library shipsGameWindowTextInputEvents, the adapter the window constructor uses; the UI does not dispose a source it was given. The mouse and the keys come from MonoInput's managers, whose own polling reads the game window as well: give them the state your host tracks instead, withKeyboardManager.Update(keyboardState)andMouseManager.Update(mouseState)(MonoInput 2.1 or later), once per frame beforeUpdate. The cursors the elements ask for go through MonoGame'sMouse.SetCursor, which needs the game window too: giveMouseCursorHandleryour own way of showing aMouseCursor(with WindowsDX itsHandleis a Windows cursor handle), or null to show none.
The Content folder of the package (the default font) is copied next to your executable, where the UI finds the font.
The game's own mouse and keys
The game reads the same mouse and keys as the UI. So a click on a button doesn't also shoot, and typing a name doesn't
also walk the player, ask the UI after its Update whether it took them:
_ui.Update(gameTime);
if (!_ui.HasMouse) HandleWorldClicks();
if (!_ui.HasKeyboard) HandleMovementKeys();
HasMouse is true while the mouse is over an element that takes the mouse (see HitTest; the root, where nothing else
is, does not count), while the buttons pressed on an element are held (a drag, a resize, a slider pulled past its end),
and while a modal window is shown. Buttons pressed where no element takes the mouse stay the game's until they are
released, also while the mouse passes over elements meanwhile, so a camera dragged across a panel goes on turning. HasKeyboard is true while an element has the keyboard, FocusedElement says which;
a press outside of it takes the keyboard away, also a press where no element takes the mouse. Layout containers that
cover the screen take the mouse as well unless their HitTest is off (a Grid, a StackPanel and a Label don't take
it by default).
ElementAt(position) finds the element the mouse would be over at a position in logical units, by the rules the UI
hovers by (the open context menu and drop down first, then windows above their siblings and children by ZIndex, only
visible elements that take the mouse, only a shown modal window's elements), without hovering anything: the root where
nothing else takes the mouse, null outside of the screen. ElementUnderMouse is the one at the mouse. The element found
can be a control's part (a list's row, a slider's thumb): walk up its Parents to the element you want.
Display scaling
Elements are laid out in logical units: one unit is one pixel at 100 %. BorrowedTorchUI.Scale sets how large a unit is
on the screen, so at 1.5 the UI is drawn one and a half times larger at the display's full resolution. The layout does
not change with the scale: sizes, margins, positions, font sizes and the mouse positions in events stay in logical units.
Only the drawing, the clipping and the reading of the mouse are scaled, and the fonts are rasterized for the scale.
Windows stretches the window of a process that is not DPI aware, which blurs it on a scaled display, and tells such a process 96 DPI everywhere. Declare the game per-monitor DPI aware before the window is created, then let the UI follow the display scale of the window's monitor:
// Program.cs, before the game creates its window
DisplayScale.DeclarePerMonitorAwareness();
using var game = new MyGame();
game.Run();
// in LoadContent, after creating the UI with the game window: 144 DPI is a scale of 1.5
_ui.FollowsDisplayScale = true;
// optional: a UI size setting of the game, multiplied with the display scale
_ui.DisplayScaleFactor = 1.25f;
FollowsDisplayScale sets Scale at once, then reads the monitor's DPI again every 30 updates and follows the window to
a monitor with another scale. A scale set by hand stays until the DPI changes. It needs the constructor that takes the
game window. To read the scale yourself, DisplayScale.DpiOf(window) gives the DPI of the monitor under the middle of
the window and DisplayScale.ScaleOf(window) the scale (DPI / 96).
The screen size stays in device pixels (the back buffer, or the size given to ApplyGameWindowSize); the root covers it
in logical units. To keep a window of 1280 x 800 units at 150 %, give it a back buffer of 1920 x 1200. A window that
moves to another monitor keeps its pixels, and the UI fills them at the new scale.
Limits: a one-unit line covers one or two device pixels at scales like 125 %, textures are resampled to the scale (give
sharper sources for crisp images), custom mouse cursors made from textures are not scaled, and a FontSystem given by
hand keeps the resolution it was created with. Draw code that begins its own sprite batch inside the UI (a
PreDrawAction) passes BorrowedTorchUI.DrawTransform to draw in logical units; a ViewPort draws in device pixels and
sizes its content by GraphicsDevice.Viewport.
Common element properties
Every element derives from BaseElement and has these properties (all of them are dependency properties):
| Property | Meaning |
|---|---|
DesiredWidth, DesiredHeight |
Size in pixels. 0 means fit to content, or stretch when the alignment is Stretch. |
MinWidth, MinHeight, MaxWidth, MaxHeight |
Size limits, 0 means no limit. |
HorizontalAlignment, VerticalAlignment |
Stretch (default), Left/Top, Center, Right/Bottom. |
Margin |
Offset from the parent, see Margins. |
Visibility |
Visible, Hidden (keeps its space), Collapsed (zero size). |
Disabled |
Greys out the element and stops mouse interaction, inherited by children. |
BackgroundColor, ForegroundColor |
Solid colors used when no textures are set. |
TexturesPath |
Content folder with the element's textures (e.g. UITextures/Button/), see the element sections. |
Transparency |
0 opaque, 1 invisible, inherited by children and combined with their own. |
HitTest |
Whether the element itself takes the mouse (the deepest one under the mouse takes it); a control passes it to its parts that take the mouse (a list's rows and scroll bars, a slider's buttons, a window's title bar and close button). |
InheritState |
None, FromParent, FromChildren or Both: the states the element shows besides its own, see below. |
CropOutsideOfParentBorder |
Clips the element to its parent. Without it the element may overflow its parent, but is still clipped by what clips the parent (a scroll view, a window's content area); tooltips, menus, drop-downs and modal windows are not clipped by the elements they open from. |
IsResizable, ResizeAreaHalfWidth, ResizeWithElementContour, ResizeContourColor |
Lets the user resize the element with the mouse; with its contour the element stays while a contour (drawn above everything) shows the new bounds, and it is resized there on release. |
DragType, DragTarget, DragAndDropRepresentation |
Mouse dragging, see Drag and drop. |
GridColumn, GridRow, GridColumnSpan, GridRowSpan |
Placement inside a Grid. |
ZIndex |
Stacking among the siblings where they overlap: the higher one is drawn above and gets the mouse there (default 0, siblings with the same one in the order they were added). The layout, the item order and the keyboard order stay as they are. In a Grid a cell goes by the highest of its items, so an item spanning other cells can be put above or below them. Non-modal windows ignore it, see Window. |
RepeatClicks, TimeBeforeRepeatStartsMs, TimeBetweenRepeatsMs, DoubleClickIntervalMs |
Click timing, passed down to the control's own parts (the scroll bars of a list repeat as the list says). |
ToolTip |
A ToolTip shown on hover. |
ContextMenu |
A ContextMenu opened by a right click, see ContextMenu. |
CustomEffect |
An Effect applied when drawing the element and its children. |
Events: OnClick, OnDoubleClick, OnKeyDown, OnMouseEnter, OnMouseLeave, OnStateChanged, OnDragAndDropStart,
OnDrop, OnDropDenied, OnDisposed. Read-only layout results: ActualWidth, ActualHeight, Location, Left, Top,
Right, Bottom.
One element has the keyboard: Focus() gives it to an element (false when it is not in the tree, hidden or disabled),
IsFocused tells whether it has it, and the typed text goes to that element only. It loses the keyboard when
another element is focused, when a press lands outside of it, and when it is hidden, disabled or removed.
A key goes to the focused element first, then up to the elements around it until one handles it: OnKeyDown gets a
KeyDownEventArgs with the Key and Handled. The built-in controls handle the keys they use (a list its navigation
keys, a text box its caret and scroll keys, an editable one every typing key too, an open context menu every key), so a
window or a panel gets the others, such as Escape or a shortcut, while something in it has the keyboard:
window.OnKeyDown += (_, e) =>
{
if (e.Key != Keys.Escape) return;
window.Hide();
e.Handled = true;
};
The element the mouse buttons were pressed on holds the mouse until they are released: nothing else is hovered or pressed meanwhile, and a click (or a check box toggle) only happens when the buttons are released over it.
An element shows the highest of its own state (hovered, pressed) and the states it takes with InheritState: its
parent's, its children's or both. A title bar with FromChildren lights up while its label is hovered; the label with
FromParent lights up with the title bar. Up an element passes its own and its children's state, down its own and its
parent's, so a state never comes back to where it came from (a list lit by a hovered row does not light its other rows).
A control's hidden parts pass states through as if they were not there, so only the elements you created decide;
parts that take the mouse themselves (a slider's buttons, a list's rows) show their own state. Clicks and drags stay
with the element actually under the mouse.
Those parts take the mouse for their control: where a part has no ToolTip, DragType or drop settings
(IsDropAllowedPredicate, OnDrop, OnDropDenied) of its own, the control's apply. A text box's tooltip shows over its
text, a text box with a DragType is dragged by its text, and a drop on a list's row is decided and taken by the list.
Your own elements inside a control, and its drop-down lists, keep their own settings. Clicks stay with the part: the
controls raise their own events for them (a selection, a value change).
Child management: AddItem, AddItemAt, AddItemsRange, AddItemsRangeAt, RemoveItem, RemoveItemAt,
RemoveItemsRangeAt, ClearItems. They act on the items only, never on the element's own parts. Elements that host
a single child expose it as Content instead, and they and the other controls without items (text elements, sliders,
progress bars...) ignore the item methods; a derived element opts out with protected override bool AcceptsItems => false.
Dispose an element with Dispose() when it is no longer needed, it is removed from its parent automatically.
What the element made itself (its parts, the text content of a button, the rows of text items) is disposed with it;
the elements you gave it (content, items, tooltip, context menu, drag representation) are only detached, so dispose
or reuse them yourself. A control's Content forgets a content that was disposed, and a disposed element can't be
added anywhere again (ObjectDisposedException).
Margins
Margin is a struct with Left, Top, Right, Bottom and implicit conversions from an int and from tuples:
element.Margin = 5; // all sides
element.Margin = (10, 20); // left, top
element.Margin = (10, 20, 30); // left, top, right
element.Margin = (10, 20, 30, 40); // left, top, right, bottom
Unlike WPF, a child's margin counts toward its parent's content size (what a parent that fits its content grows to)
only on the side the child is aligned to: the left / top margin for Left / Top, the right / bottom margin for
Right / Bottom, both for Center, and both for a Stretch child without a DesiredWidth / DesiredHeight (with
one, only the left / top margin). The margin on the other side is not counted, so e.g. in a horizontal StackPanel the
Margin.Right of a Left aligned item adds no spacing: put the gap on the left (or top) margin of the next item.
Elements
Every element has a constructor taking an optional name, used by GetElementByName. The name never changes (Name
is read-only); the parts an element makes are named after it, such as listRowsContainer for a list named list.
Border
A frame around a single Content element. Thickness is the border width per side. The content area, which
BackgroundColor fills and the content sits in, is inset by the thickness, or by ContentAreaMargin (optional)
from the border's outer edges: smaller than the thickness, it lets the background reach under a frame's transparent
pixels (a thin curved frame). Space between the frame and the content is the content's own Margin: around all of
it in a border that fits its content, the content stretches or is centered (a Left / Top one counts only its left /
top margin there, see Margins). Textures: LeftTop, RightTop, LeftBottom, RightBottom, Left,
Right, Top, Bottom.
var border = new Border("border")
{
Thickness = (2, 2, 2, 2),
ForegroundColor = Color.DarkSlateGray, // border color
BackgroundColor = Color.WhiteSmoke, // content area background
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Content = new RichTextBox { Text = "Framed", Margin = 10 } // 10 from the frame, on the background
};
Button
Type is Normal, Repeat (fires OnClick repeatedly while held) or Toggle (ToggledOn, OnToggled).
Text creates a centered Label content styled by TextStyle (a LabelStyle), or set any element as Content
(a RichTextBox for formatted text, for example).
Solid colors: NormalColor, HoverColor, PressedColor, ToggledColor. Textures: Normal, Hover,
Pressed, Toggled.
var button = new Button("playButton")
{
Text = "Play",
DesiredWidth = 120,
DesiredHeight = 36,
NormalColor = Color.SteelBlue,
HoverColor = Color.LightSteelBlue,
PressedColor = Color.Navy,
TextStyle = new LabelStyle { FontSize = 18, ForegroundColor = Color.White }
};
button.OnClick += (sender, e) => StartGame();
var toggle = new Button("muteButton")
{
Type = ButtonType.Toggle,
Content = new Image { Source = Content.Load<Texture2D>("UITextures/Icons/Mute"), Fill = ImageFill.Center }
};
toggle.OnToggled += (sender, isOn) => SetMuted(isOn);
var textured = new Button("texturedButton")
{
TexturesPath = "UITextures/Button/", // Normal, Hover, Pressed (+ Toggled) textures inside
DesiredWidth = 64,
DesiredHeight = 64
};
CheckBox
Type is CheckBox or RadioButton. Radio buttons sharing a GroupId uncheck each other, the first one
added to a group starts checked. Direction puts the box left or right of the content.
Solid colors: CheckedSolidColor, UncheckedSolidColor (blue and gray unless set, from DefaultSettings). Textures:
Checked, Unchecked.
var checkBox = new CheckBox("fullscreen")
{
Text = "Fullscreen",
DesiredHeight = 24,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
CheckedSolidColor = Color.LimeGreen,
UncheckedSolidColor = Color.Gray
};
checkBox.OnCheckedUnchecked += (sender, isChecked) => SetFullscreen(isChecked);
var easy = new CheckBox("easy") { Type = CheckBoxType.RadioButton, GroupId = "difficulty", Text = "Easy", DesiredHeight = 24 };
var hard = new CheckBox("hard") { Type = CheckBoxType.RadioButton, GroupId = "difficulty", Text = "Hard", DesiredHeight = 24 };
ColorPicker
A color wheel: the hue goes around the center, the saturation grows from white at the center to the full color at
the edge. A click picks a color, Brightness (0..1) scales it, SelectedColor is the result. The pointer on the
picked color is a black ring 9 pixels across, made in code; PointerStyle (an ImageStyle) styles it, and its
Source replaces the ring with a picture of your own (the pointer is centred on the picked pixel at its size).
var colorPicker = new ColorPicker("picker")
{
DesiredWidth = 256,
DesiredHeight = 256,
Brightness = 0.9f,
// a picture of your own instead of the ring
PointerStyle = new ImageStyle { Source = Content.Load<Texture2D>("UITextures/Crosshair") }
};
colorPicker.OnSelectedColorChanged += (sender, color) => tint = color;
ComboBox
A selection image, a toggle button and a drop-down ListBox. Items are added like to a ListBox
(AddTextItem, AddItem, or ItemsSource with an ItemsTemplate), selection goes through Select, SelectAt,
SelectSource, SelectedItem (and SelectedSource, its source object), SelectedIndex, their DPs and
OnItemSelect (the sender is the combo box, the item a row of its drop-down list). Part styles: SelectionStyle, ToggleButtonStyle,
ListBoxStyle.
var comboBox = new ComboBox("resolution")
{
DesiredWidth = 200,
DesiredHeight = 30,
ToggleButtonStyle = new ButtonStyle { DesiredWidth = 30, NormalColor = Color.Gray, HoverColor = Color.DarkGray },
ListBoxStyle = new ListBoxStyle { NormalItemColor = Color.White, HoverItemColor = Color.LightBlue }
};
comboBox.AddTextItem("1280 x 720");
comboBox.AddTextItem("1920 x 1080");
comboBox.SelectAt(0);
comboBox.OnItemSelect += (sender, item) => ApplyResolution(item.Index);
ContextMenu
A menu opened by a right click on its element (element.ContextMenu = menu; the click is released over the element, or
over an element inside it without a menu of its own) or by Open(point), drawn above everything and kept on the screen
(Placement, MarginFromMouseCursor); a menu or sub-menu taller than the screen is as tall as it and scrolls its
items. Its items are ContextMenuItems (a text or any element as content, an element
added directly is put in one; AddTextItem(text) adds an item showing a text and returns it), Separators, or the objects of an ItemsSource (with ItemsTemplate, a label by
default; a BindableCollection<T> is followed). An item can be checkable (IsCheckable, IsChecked, toggled when it is
chosen) and open a SubMenu, a ContextMenu of its own, on hover or on click (SubMenusOpenType). While one item of a
menu is checkable, every item keeps the check mark's column, so the contents line up; while one opens a sub-menu, every
item keeps the arrow's column, so the items end alike. A sub-menu opens right next to its item, over the menu's edge,
its first item level with the item. On hover, it stays open while the mouse is over its item, over the sub-menu or
over a sub-menu opened from it; anywhere else (another item, a border, outside) the sub-menus close and the menu itself
stays open. A sub-menu the keys opened stays until the mouse moves. On click, a click on the item opens or closes its
sub-menu; a press on a menu outside of its items (its border, a separator) closes the sub-menus opened from that menu.
While it is open the menu has the keyboard: Up and Down move over the items (separators are passed over), Enter or Space
chooses one, Right opens a sub-menu, Left and Escape close one. Choosing an item raises its OnClick and the menu's
OnItemSelect and closes the menu (the element that had the keyboard gets it back); a press somewhere else closes it as
well. Looks: BorderStyle, ListBoxStyle, CheckIconStyle, ExpandIconStyle.
var sortMenu = new ContextMenu("sort");
sortMenu.AddTextItem("By name");
sortMenu.AddTextItem("By date");
var menu = new ContextMenu("listMenu");
menu.AddTextItem("Copy").OnClick += (sender, e) => CopySelection();
menu.AddItem(new Separator { DesiredHeight = 1, Margin = (4, 3, 4), BackgroundColor = Color.Gray });
menu.AddItem(new ContextMenuItem("Show grid") { IsCheckable = true, IsChecked = true });
menu.AddTextItem("Sort").SubMenu = sortMenu;
menu.OnItemSelect += (sender, item) => Log(item);
list.ContextMenu = menu;
Grid
Rows and columns defined in pixels (AddColumnDefinition(100)), auto sized (AddColumnDefinition()) or
proportional (AddColumnDefinition(1.0f)). Children pick their cell with GridColumn / GridRow and can span
with GridColumnSpan / GridRowSpan. ShowLayout + LayoutColor draw the cell lines for debugging.
var grid = new Grid("layout");
grid.AddColumnDefinition(200); // fixed sidebar
grid.AddColumnDefinition(1.0f); // the rest
grid.AddRowDefinition(); // auto: as tall as the header content
grid.AddRowDefinition(1.0f);
grid.AddItem(new RichTextBox("header") { Text = "Title", GridColumn = 0, GridRow = 0, GridColumnSpan = 2 });
grid.AddItem(new ListBox("sidebar") { GridColumn = 0, GridRow = 1 });
grid.AddItem(new Image("preview") { GridColumn = 1, GridRow = 1, Source = previewTexture, Fill = ImageFill.Center });
Image
Draws a Source texture with a Fill mode: Stretch, Center, Tile, TileX, TileY.
Source accepts a Texture2D or a content path (a string is loaded through the ContentManager, so it names a compiled
.xnb asset, without the extension).
The source is drawn straight to the screen every frame (only the tiles in view for the tile modes), not kept in a
texture of the image's size: an image takes no texture memory of its own and can be larger than the GPU texture size
limit (a tiled background of a long scrolled page).
The PNG files of this repository's Content folder (UITextures/...) are plain files, not compiled assets, so
Content.Load and a string path can't read them: load them with Texture2D.FromStream, as the demo does (the demo
project copies the folder next to the executable). The texture is yours, dispose it when the game unloads. The
LoadPng helper below is used by the other snippets of this file that load a PNG.
// a PNG file, e.g. from the Content folder next to the executable
private Texture2D LoadPng(string relativePath)
{
using var stream = File.OpenRead(Path.Combine(AppContext.BaseDirectory, "Content", relativePath));
return Texture2D.FromStream(GraphicsDevice, stream);
}
var logo = new Image("logo")
{
Source = LoadPng("UITextures/Logo/Kindling.png"),
Fill = ImageFill.Center,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Top,
Margin = (0, 20)
};
var background = new Image("background")
{
Source = Content.Load<Texture2D>("UITextures/Pattern"), // a compiled asset of your own (Pattern.xnb)
Fill = ImageFill.Tile // stretches over the parent (default alignment)
};
Label
Plain text in one or more lines, drawn straight from the font atlas: no scrolling, editing or rich formatting,
which makes it the cheap choice for captions and list rows (AddTextItem and the default items template use it).
Text, FontSize, FontPath, TextMargin, TextAlignment, VerticalTextAlignment (see RichTextBox), WrapType
(wraps only with a fixed or stretched width), LineSpacing; LineCount tells how many lines the text took.
TextRotation (Clockwise reads from the top down, CounterClockwise from the bottom up, UpsideDown) turns the text
with its frame: the margins, both alignments and the wrapping turn with it, so a label turned on its side wraps at its
height and, fitted to its text, swaps its width and height. Only the drawing turns: clicks and cropping keep the label's
box.
var caption = new Label("caption")
{
Text = "Score",
FontSize = 18,
ForegroundColor = Color.White,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Margin = (8, 4)
};
var description = new Label("description")
{
Text = "A long description that wraps inside 200 pixels.",
WrapType = TextWrap.Wrap,
DesiredWidth = 200,
TextAlignment = TextAlignment.Center,
LineSpacing = 2
};
ListBox
Scrollable list with single or multiple selection (SelectionMode), optional alternating row colors (UseDualColors,
NormalItemColor, AlternativeItemColor; a Separator row lies on the normal color and the rows around it alternate as
if it were not there) and state colors (HoverItemColor,
PressedItemColor, SelectedItemColor). Any element can be an item, AddTextItem adds a Label row and
AddTextItems adds many of them in one batch (AddItemsRange batches too: rows are indexed and laid out once).
A list without a size of its own fits its rows within its min and max sizes; when MaxHeight makes it shorter than
the rows, it gets wider by the vertical scroll bar, so the bar takes no room from the rows (the same for MaxWidth).
Shift / Ctrl clicks extend the selection in Multiple mode. Events: OnItemSelect, OnItemsSelect.
Items is a live, read-only view of the rows (ListBoxItem, with Index, Content, Source and IsSelected),
Count is the number of rows, SelectedIndices and SelectedSources list the selection by index and by source object.
var listBox = new ListBox("levels")
{
DesiredWidth = 240,
DesiredHeight = 300,
SelectionMode = ListBoxSelectionMode.Single,
UseDualColors = true,
NormalItemColor = Color.White,
AlternativeItemColor = Color.WhiteSmoke,
HoverItemColor = Color.LightBlue,
SelectedItemColor = Color.CornflowerBlue,
ScrollableContainerStyle = new ScrollableContainerStyle { ScrollBars = ScrollBars.Vertical, ScrollBarsThickness = 12 }
};
listBox.AddTextItem("Forest");
listBox.AddTextItems(["Desert", "Mountains", "Swamp"]);
listBox.AddItem(new Separator { DesiredHeight = 1, BackgroundColor = Color.Gray });
listBox.AddItem(new CheckBox { Text = "Custom item", DesiredHeight = 24 });
listBox.OnItemSelect += (sender, item) => LoadLevel(item?.Index ?? -1);
listBox.SelectAt(0);
Items can also come from a view model, see Bindings.
Virtualization
With VirtualizationMode = Fixed and an ItemHeight every row is ItemHeight pixels high and only the rows in
view (plus three above and below, and the selected one) get elements. Rows are kept as light records, so lists of
hundreds of thousands of rows fill in milliseconds, and the row elements that scroll out are recycled for the rows
that come in: a template generated content is handed to IItemsTemplate.UpdateItemElement, which updates it (the
default text template does) or returns a new element (the default: one generated again, the old one is disposed).
Elements added with AddItem are detached while out of view and re-attached when they return, never disposed.
In Fixed mode Items, SelectedItem and SelectedItems only cover the rows that currently have an element;
selection, SelectedIndex, SelectedIndices, SelectedSources and SelectSource work on every row. Collapsed
rows still take their ItemHeight, and the horizontal extent grows with the widest row seen so far.
Scrolling and keyboard
ScrollIntoView(index) scrolls a laid out list just enough to show the row, SelectNext, SelectPrevious and
MoveSelection(delta) select and scroll (separators are skipped, RowsPerPage rows fit the view). A list that has
the keyboard (it was pressed or given Focus(), the open list of a ComboBox takes it) reacts to Up, Down, PageUp,
PageDown, Home and End (keys arrive from the game window, or the ITextInputEvents passed to BorrowedTorchUI).
var log = new ListBox("log")
{
DesiredWidth = 400,
DesiredHeight = 300,
VirtualizationMode = ListBoxVirtualizationMode.Fixed,
ItemHeight = 22
};
log.AddTextItems(Enumerable.Range(0, 200_000).Select(i => $"Line {i}"));
log.SelectAt(199_999); // the selected row is realized even while it is out of view
ProgressBar
Min, Max (0 and 1 unless set), Value and Orientation. BackgroundColor is the track, ForegroundColor the
bar. Textures: Background, Bar.
var progressBar = new ProgressBar("loading")
{
DesiredWidth = 300,
DesiredHeight = 20,
Min = 0,
Max = 100,
Value = 35,
BackgroundColor = Color.DimGray,
ForegroundColor = Color.LimeGreen
};
RichTextBox
Text display and editing. Type is ReadOnly or ReadWrite (click to place the cursor, typing, selection,
clipboard, undo / redo with Ctrl+Z / Ctrl+Y). An editable box has the keyboard while its cursor is shown; it raises
OnApply when the editing ends: Enter, a press somewhere else, or another element focused. A read-only box takes the
keyboard with a press too, without a cursor: the arrows scroll it by a line, Page Up / Page Down by a page and Home / End
to the start or the end (along the text when it is not wrapped). WrapType, TextAlignment,
TextMargin, LineSpacing, FontSize, FontPath (TTF file, otherwise the bundled UbuntuMono is used),
ScrollBars, TextFilter (transforms every assigned text) and InputType (Insert / Overwrite).
With EnterTypesLineBreak Enter types a line break, and Ctrl+Enter ends the editing instead.
VerticalTextAlignment (Top, Center, Bottom) places the lines in a box taller than its text, such as a one-line
input of a fixed height, whatever the font size; the caret, the selection, the clicks and the links follow. A text that
does not fit the view (it scrolls) starts at the top margin, and a box fitted to its text has no room to align in.
With Formatting = Rich (read-only boxes) words can carry instructions [c=0,a=1,i=2]word[/] that index
the static RichTextBox.RichColors, RichActions (clickable links) and RichImages lists. [o=n] outlines
the letters in RichColors[n] (RichOutlineThickness units wide), [u=1] underlines and [s=1] strikes
through in the text's own colour (0 turns them off); [/] ends all of it. A self-closing tag such as
[i=0/] applies to its own place only (an image), and the formatting around it goes on. [f=n] draws in the font
file RichTextBox.RichFonts[n] and [z=n] n units high; a line is as high as its tallest letters need, on one
baseline.
AnimateText(text) types the text out with CharacterPrintDelayMs per character.
The text is not rendered into a texture: every frame only the lines that intersect the visible area are drawn straight from the font atlas, so the text length is limited by memory for the layout, not by the GPU texture size.
RichTextBox.RichColors.Add(Color.Orange);
RichTextBox.RichActions.Add(() => OpenHelp());
var label = new RichTextBox("hint")
{
Text = "Press [c=0]Space[/] to jump, or read the [a=0]help[/].",
Formatting = RichTextBoxFormatting.Rich,
WrapType = TextWrap.Wrap,
DesiredWidth = 300,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
ForegroundColor = Color.White,
BackgroundColor = Color.Transparent
};
var input = new RichTextBox("name")
{
Type = RichTextBoxType.ReadWrite,
DesiredWidth = 200,
DesiredHeight = 28,
TextMargin = (4, 4),
BackgroundColor = Color.White,
TextFilter = text => text.Length > 16 ? text[..16] : text
};
input.OnApply += (sender, text) => playerName = text;
input.OnTextChanged += (sender, text) => Validate(text);
ScrollableContainer
Scrolls its items when they are larger than the container. ScrollBars (None, Vertical, Horizontal,
Both; Both unless set, a bar shows only where the content needs it), ScrollBarsThickness, ScrollBarsStyle (a
SliderStyle; unless set, one track color on both sides of the thumb), HorizontalScrollingValue /
VerticalScrollingValue (0..1). The mouse wheel scrolls while the mouse is over the container, PageUp, PageDown,
PageLeft and PageRight scroll by the view's size (the older VerticalPageIncrease / VerticalPageDecrease and
HorizontalPageIncrease / HorizontalPageDecrease are obsolete: "increase" followed the vertical scroll bar's value and
scrolled up). Items are the elements that scroll; the container's Children are its view and scroll bars.
var scrollable = new ScrollableContainer("log")
{
DesiredWidth = 400,
DesiredHeight = 200,
ScrollBars = ScrollBars.Vertical,
ScrollBarsThickness = 14,
ScrollBarsStyle = new SliderStyle { ThumbSolidColor = Color.Gray, ButtonsSolidColor = Color.DarkGray }
};
scrollable.AddItem(new StackPanel("logLines") { Orientation = Orientation.Vertical });
scrollable.VerticalScrollingValue = 1; // scroll to the bottom
Separator
An empty element, used as a divider inside lists and panels: a gray line (DefaultSettings.DefaultSeparatorColor)
at least 1 pixel thick, across whichever way it stretches, unless given a color and size of its own.
var separator = new Separator { DesiredHeight = 2, BackgroundColor = Color.Gray, Margin = (0, 4, 0, 4) };
Slider
Min, Max (0 and 1 unless set), Value, optional Tick snapping with TickPlacement, TickSize, TickOffset,
TickPassedColor, TickRemainingColor. Type: Slider, SliderWithCaps (end buttons jump to min / max),
ScrollBar, ScrollBarNoButtons. MoveToPoint jumps to the clicked position instead of paging.
Solid colors: ButtonsSolidColor, LineDecreaseSolidColor, LineIncreaseSolidColor, ThumbSolidColor.
Textures (horizontal): LeftButton, RightButton (or LeftEnd, RightEnd), HorizontalDecrease,
HorizontalIncrease, ThumbLeft, ThumbHorizontal, ThumbRight; vertical uses DownButton, UpButton,
BottomEnd, TopEnd, VerticalDecrease, VerticalIncrease, ThumbBottom, ThumbVertical, ThumbTop.
var volume = new Slider("volume")
{
DesiredWidth = 200,
DesiredHeight = 20,
Min = 0,
Max = 100,
Value = 50,
Tick = 5,
TickPlacement = TickPlacement.BottomOrRight,
TickSize = new Point(1, 4),
TickOffset = 2,
ThumbScale = new Vector2(0.6f, 1.0f),
LineDecreaseSolidColor = Color.SteelBlue,
LineIncreaseSolidColor = Color.LightGray,
ThumbSolidColor = Color.White
};
volume.OnValueChanged += (sender, value) => SetVolume(value / 100f);
StackPanel
Stacks its items vertically or horizontally (Orientation) and fits to their size. Items lists them in order; the
panel's Children are the wrappers it puts each item in.
var menu = new StackPanel("menu")
{
Orientation = Orientation.Vertical,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
// the gaps are top margins: the bottom margin of an item adds nothing to the size of the panel (see Margins)
menu.AddItem(new Button { Text = "New game", DesiredWidth = 200, DesiredHeight = 40 });
menu.AddItem(new Button { Text = "Options", DesiredWidth = 200, DesiredHeight = 40, Margin = (0, 8) });
menu.AddItem(new Button { Text = "Quit", DesiredWidth = 200, DesiredHeight = 40, Margin = (0, 8) });
Stencil
Shows SourceTexture through StencilTexture: where a stencil pixel is close to KeyColor (its color within
Tolerance, and its alpha as well) the source pixel shows, the other stencil pixels stay (a frame around a picture).
var stencil = new Stencil("portrait")
{
SourceTexture = LoadPng("UITextures/Stencil/Source.png"), // LoadPng: see Image
StencilTexture = LoadPng("UITextures/Stencil/Stencil.png"),
KeyColor = Color.Black,
Tolerance = 0.1f,
DesiredWidth = 128,
DesiredHeight = 128
};
TabControl
Not an element but a helper that maps tab elements to content elements and shows only the content of the
open tab: the first one added, then the last one pressed with the left button or opened with OpenTab. The tabs
and the contents are placed by you (a StackPanel of buttons plus a Grid cell, for example). CurrentTab and
CurrentOpenedContent tell which one is open, and OnTabOpened is raised when another one opens (null when the
last tab was removed), e.g. to mark the open tab. A removed tab's content is visible again, and a disposed tab or
content leaves the control by itself.
var tabs = new TabControl();
tabs.OnTabOpened += (_, tab) => statusLabel.Text = $"Open: {tab?.Name}";
tabs.AddTab(audioTabButton, audioPanel);
tabs.AddTab(videoTabButton, videoPanel);
tabs.OpenTab(videoTabButton);
tabs.RemoveTab(videoTabButton);
ToolTip
Attached to any element through its ToolTip property. Text or Content, Placement relative to the
mouse cursor (BottomRight unless set), MarginFromMouseCursor and TimeBeforeShowMs.
button.ToolTip = new ToolTip("saveTip")
{
Text = "Save the current game (Ctrl+S)",
Placement = ToolTipPlacement.BottomRight,
MarginFromMouseCursor = (12, 12),
TimeBeforeShowMs = 400,
BackgroundColor = Color.LightYellow
};
TreeView
A tree of TreeViewItems shown in a ListBox. It is filled from data with ItemsSource, ChildrenSelector (the
children of an object, null for a leaf) and optionally ItemsTemplate (a label with the object's text when none is
set); every item's Source is its object. Only the first level is made at first: a branch of the data starts
collapsed and makes the items of its children the first time it is expanded (HasLeaves tells that it has some
before that). An items source or a children collection that is a BindableCollection<T> is followed: added or removed
objects add or remove their items. An object that appears again below itself (a cycle in the data) shows no children
there. Making the items again (another ItemsSource, ChildrenSelector or ItemsTemplate) keeps the expanded
branches and the selected object. While an ItemsSource is set, items are not added or removed in code. Without one, AddItem adds any element as a leaf (in a TreeViewItem made around it),
AddTextItem(text) adds a label item and returns it, and items are nested by adding to a TreeViewItem (its own
AddItem and AddTextItem). A TreeViewItem you add keeps its name; the items the tree view makes are named after
the item they join (levelsLeaf0).
Any item can be selected, a branch as well as a leaf: with a click (which also expands or collapses a branch), Up and
Down, SelectedItem (the branches above it are expanded) or SelectSource(object) (also an object in a branch that
was not expanded yet). OnItemSelect reports it, and
SelectedItem can be bound to a property holding the source object. IsExpanded of an item, ExpandAll() and
CollapseAll() open and close branches; Right expands a branch or goes to its first leaf, Left collapses it or goes
to its parent. Expand icon: ExpandIconStyle (by default an 8 x 8 block centred before the item), FoldedIconColor,
ExpandedIconColor, or the FoldedIcon / ExpandedIcon textures; SubItemsShift indents children.
public sealed class Folder(string name, params Folder[] children)
{
public BindableCollection<Folder> Children { get; } = [.. children];
public override string ToString() => name;
}
var folders = new BindableCollection<Folder> { new("Levels", new("Forest"), new("Desert")) };
var tree = new TreeView("files")
{
DesiredWidth = 240,
DesiredHeight = 300,
SubItemsShift = (16, 0),
ChildrenSelector = folder => ((Folder)folder).Children,
ItemsSource = folders
};
tree.OnItemSelect += (sender, item) => Open((Folder)item?.Source);
folders.Add(new Folder("Characters", new Folder("Knight"))); // shown at once
tree.ExpandAll(); // makes the items of the whole data
// or built in code (without an ItemsSource)
var levels = tree.AddTextItem("Levels");
levels.AddTextItem("Forest");
levels.AddItem(new Label { Text = "Desert" }); // any element, in an item made around it
ViewPort
Reserves a rectangle, sets the GraphicsDevice.Viewport to it and runs DrawInstructions, so a 3D scene or
another 2D render can be embedded inside the UI. MinDepth / MaxDepth map to the viewport depth range.
DeviceBounds is the view port's rectangle in device pixels (what GraphicsDevice.Viewport is set to), and the
drawing is clipped to its HitRectangle, the part a parent does not crop away. The drawing comes over the view port's
background and under its children, so items added to it (a caption, buttons over the scene) lie on top.
var viewPort = new ViewPort("scene")
{
DesiredWidth = 640,
DesiredHeight = 360,
DrawInstructions = () => sceneRenderer.Draw(GraphicsDevice)
};
Window
A draggable window with a border, a title bar and a content area. TitleBar defaults to a
DefaultWindowTitleBar (Title, CloseButton, Background), Content holds the body, IsModal windows
shade everything else and block input to it. Show() / Hide() toggle the window, IsResizable lets the
user resize it. The border is styled through BorderStyle.
Non-modal windows are drawn above their sibling elements, in the order they were shown. A window comes to the front of
its sibling windows when it is pressed anywhere or an element in it is focused (a window in a window brings the outer
one along), and BringToFront() does it from code.
var window = new Window("settings")
{
DesiredWidth = 400,
DesiredHeight = 300,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
IsModal = true,
IsResizable = true,
BorderStyle = new BorderStyle { Thickness = 2, ForegroundColor = Color.Black, BackgroundColor = Color.Wheat },
Content = settingsGrid
};
var titleBar = (DefaultWindowTitleBar)window.TitleBar;
titleBar.Title.Text = "Settings";
titleBar.CloseButton.Text = "x";
_ui.AddElementToRoot(window);
window.Hide();
// ...
window.Show();
DragAndDropRepresentation
The element shown under the mouse while dragging, see Drag and drop.
Layout and custom elements
The layout runs when something changed, in two walks down the tree: measure finds every element's size, arrange
gives every element its final size (ActualWidth, ActualHeight) and position (Location, in screen coordinates). One
measure and one arrange settle a change; nothing reacts to a size while they run.
An element's size along each side is its DesiredWidth / DesiredHeight when it has one; a Stretch element takes the
slot its parent gives it (less its margins); any other element fits its content. A child stretched in a parent that fits
its content counts with the size of its own content and its margins, as in WPF: a label in a stack panel or an auto grid
row has its text's height, and an unwrapped label widens a fitted panel to its line. Wrapping text is the exception
along the width: it takes the width the rest of the content decides and wraps there, instead of widening the parent to
one long line. When nothing else gives a width, as for a label alone in a fitted panel, the text keeps its one line (as
in WPF), and a MaxWidth on the parent makes it wrap. MinWidth ... MaxHeight limit the result.
A custom element derives from BaseElement (or from GenericStyleAndMouseCursorsData<TStyle> to have a general style)
and overrides two methods:
MeasureContent(int width, int height)measures the children and returns the size of the content.width/heightare the element's own size where it is known (fixed or stretched) and-1where the element fits its content: then it takes the returned size. Measure a child withchild.Measure(slotWidth, slotHeight)(the space you give it,-1for a size you don't know yet) orchild.MeasureAt(width, height)(a size of your choice,-1for its own), then readchild.MeasuredWidth/MeasuredHeight(andMeasuredContentWidth/MeasuredContentHeight, what its content needs whatever size it was given). The default lays the children over each other, each placed by its margins and alignment.ArrangeContent()places the children inside the element's finalBounds:child.Arrange(slot)places it in a slot by its own margins and alignment,child.ArrangeAt(bounds)orchild.ArrangeAt(position)puts it exactly there.
An element whose final size differs from the measured one is measured again at it before it is arranged.
ActualWidthChangedHandlerOverride and OnActualWidthChanged tell about a new size after it was given; laying the parts
out there is too late. A setting of the element's own that changes the layout calls InvalidateMeasure() (or
InvalidateArrange() when only the children move).
// its items side by side, each at its own width and at the row's height, with a gap between them
public class Row : BaseElement
{
private int _gap;
public int Gap
{
get => _gap;
set
{
_gap = value;
InvalidateMeasure();
}
}
public Row(string name = null) : base(name)
{
}
protected override Point MeasureContent(int width, int height)
{
var contentWidth = 0;
var contentHeight = 0;
foreach (var child in Children)
{
child.MeasureAt(-1, height);
contentWidth += child.MeasuredWidth + _gap;
contentHeight = Math.Max(contentHeight, child.MeasuredHeight);
}
return new Point(Math.Max(contentWidth - _gap, 0), contentHeight);
}
protected override void ArrangeContent()
{
var x = Left;
foreach (var child in Children)
{
child.ArrangeAt(new Rectangle(x, Top, child.MeasuredWidth, ActualHeight));
x += child.MeasuredWidth + _gap;
}
}
}
Styles
Every element type X has an XStyle class with the same properties. A style sets values with a lower
priority than direct assignments (ManualAssign > StyleOverride > GeneralStyle), so a property set in
code always wins and can be released again with element.<Property>DP.ClearValue(ValueSources.ManualAssign).
- A style applies only the properties assigned to it (also when assigned their type's default value). A new style
has none:
new ButtonStyle { NormalColor = Color.Red }changes the color and nothing else.style.IsSet(name)tells whether a property is assigned,style.Unset(name)takes it back out. X.GeneralStyle(static) applies to everyX, changing one of its properties updates all of them. It lies over the framework defaults ofX: a property it leaves unset takes its default (it starts as a copy of the defaults). Changes are delivered to the elements in the tree; an element created or detached while a change happens catches up when it is attached.element.StyleOverrideapplies to one element, over its general style.- Every element, also one without a style class (e.g.
Grid), takes its double click interval, repeat timings and resize area fromDefaultSettings. - Styles are cloneable (
style.Clone(), with the same properties assigned), nested styles (e.g.ButtonStyle.TextStyle) are cloned too.
// every button
Button.GeneralStyle = new ButtonStyle
{
DesiredHeight = 36,
NormalColor = new Color(60, 60, 70),
HoverColor = new Color(80, 80, 95),
PressedColor = new Color(40, 40, 50),
TextStyle = new LabelStyle { FontSize = 16, ForegroundColor = Color.White }
};
// one special button
var danger = new Button { Text = "Delete", StyleOverride = new ButtonStyle { NormalColor = Color.DarkRed, HoverColor = Color.Red } };
// tweaking the general style later updates every existing button
Button.GeneralStyle.DesiredHeight = 40;
Mouse cursors work the same way: BaseElement.DefaultMouseCursorsSet for everything,
X.GeneralMouseCursorsSet per element type and element.MouseCursorsSetOverride per element.
A MouseCursorsSet has HoverCursor, PressedCursor, DragAndDropCursors, ResizeCursors and
RichTextCursors. The parts of a control show its cursors: a set given to a control (MouseCursorsSetOverride)
reaches the controls inside it as well (the scroll bars of a list, the list of a tree view or combo box, the title bar
of a window), unless they have a set of their own; without one they keep their type's GeneralMouseCursorsSet. Your
own elements placed in a control keep their own cursors.
The default set shows the arrow over the elements, the resize cursors along the edges of a resizable element, the text
cursor over the text of an editable RichTextBox and the hand over a link of a rich text. A drag shows the hand over
what can be dragged, while it is dragged and over an element that takes the drop, and the "no" cursor over one that
doesn't. A disabled element shows the plain hover cursor of its set (the arrow), whatever it would show enabled.
Button.GeneralMouseCursorsSet = new MouseCursorsSet
{
// LoadPng: see Image (the cursor textures are PNG files, not compiled assets)
HoverCursor = MouseCursor.FromTexture2D(LoadPng("UITextures/MouseCursors/ArrowHover.png"), 0, 0),
PressedCursor = MouseCursor.FromTexture2D(LoadPng("UITextures/MouseCursors/ArrowPressed.png"), 0, 0)
};
Every element shows and works without any setting, in a light theme: black text, wheat windows, white lists, combo boxes and context menus, gray controls with a blue accent for what is on or done (a checked box, the passed part of a slider or progress bar, a toggled button). Buttons are lit under the mouse and when pressed, list rows when hovered, pressed and selected; borders have a 1 pixel frame; scroll bars show where the content needs them; sliders and progress bars go from 0 to 1; a combo box has a button to open it; a tooltip has a background and shows below right of the pointer; a tree view indents its children; a separator is a gray line. What you set, in code, a style override or a general style, replaces any of it.
DefaultSettings holds these framework-wide defaults (the colors and sizes above, font size, text colors, double click
and repeat intervals, tooltip delay) and can be changed before elements are created, to re-theme everything at once.
Dependency properties
Every property Foo of an element is backed by a FooDP property of type DependencyProperty<T>, created the first
time it is used (set, bound, subscribed to, or read through FooDP): reading Foo does not create it, so an element
pays only for the properties it uses.
button.DesiredWidthDP.SetValue(120); // same as button.DesiredWidth = 120
button.DesiredWidthDP.ClearValue(ValueSources.ManualAssign); // back to the style value
button.DesiredWidthDP.OnPropertyChanged += width => Console.WriteLine(width);
button.DesiredWidthDP.PreAction = (ref int value, ref bool canProceed) => value = Math.Max(value, 50);
OnPropertyChanged (and the element's own reaction) comes when the value in effect changes: setting by hand the
value a style already gives, or clearing it again, raises nothing.
For a tool showing an element's tree and properties: element.ValueSourceOf("Foo") tells where the value of Foo
comes from now (ManualAssign, StyleOverride, GeneralStyle, or None for its default) without creating its
FooDP, and is null for a name that is no dependency property of the element; element.IsPart tells a control's own
parts (a button's label, a combo box's list) from what it was given.
The FooDP properties, the wrapping properties and the style classes are generated at build time by the
BorrowedTorch.UIDPGenerator package from the .dpg files next to each element (Elements/Button/Button.dpg
produces Button.g.cs and Styles/ButtonStyle/ButtonStyle.g.cs). The generated *.g.cs files are not
committed. To add a property to an element, add a <DP type="T">Name</DP> line to its .dpg file and build; what
the element does when the value changes is set once per class, on the shared FooDPActions (in the class's static
constructor; a second set throws). An element of your own project gets its dependency properties and style the same
way with BorrowedTorch.UIDPGenerator 4.0.0 or later: its README describes the .dpg file and the hand-written half
(a style overrides SetDefaults as protected override for its framework defaults).
Bindings
Dependency properties can be bound to a property of any object. When the object derives from Bindable and
calls PropertyChangedInvoke, the element follows its changes. Called from a property's setter without a name, it
names that property ([CallerMemberName]); another property is named with nameof, and an empty or null name
(PropertyChangedInvoke(string.Empty)) means every property changed. BindableCollection<T> is an observable list
for item sources.
public class SettingsViewModel : Bindable
{
private string _playerName = "Player";
private float _volume = 0.5f;
public string PlayerName { get => _playerName; set { _playerName = value; PropertyChangedInvoke(); } }
public float Volume { get => _volume; set { _volume = value; PropertyChangedInvoke(); } }
public BindableCollection<string> Levels { get; } = [];
}
var vm = new SettingsViewModel();
nameBox.TextDP.Bind(vm, nameof(vm.PlayerName), BindingMode.TwoWay);
volumeSlider.ValueDP.Bind(vm, nameof(vm.Volume), BindingMode.TwoWay);
levelsList.ItemsSourceDP.Bind(vm, nameof(vm.Levels), BindingMode.OneWay);
vm.Levels.Add("Forest"); // the list box gets a new row
BindingMode is OneWay (source to element), OneWayToSource (element to source) or TwoWay. The source's
notification of a two-way write is no change for the element (a value the source changed on the way, e.g. clamped, is
taken), and a notification without a new value raises nothing; a collection is taken again, its items may have changed.
An IConverter translates between the two types. For item sources an IItemsTemplate turns each source
object into an element (the default template renders ToString() in a Label). A template that also overrides
UpdateItemElement lets a virtualized list update its elements for other source objects instead of generating new
ones (it returns the element to show: the same one updated, or a new one, which replaces it):
public class LevelTemplate : IItemsTemplate
{
public BaseElement GenerateItemElement(object data) =>
new CheckBox { Text = (string)data, DesiredHeight = 24, HitTest = false };
public BaseElement UpdateItemElement(BaseElement element, object data)
{
((CheckBox)element).Text = (string)data;
return element;
}
}
levelsList.ItemsTemplate = new LevelTemplate();
Animations
An Animation<T> drives one or more targets of type T over a time line of durationMs: dependency properties
(AddDependencyProperty), or any property through its setter (AddTarget, with the element it belongs to).
SmoothAnimationFrame<T> interpolates between two values with an optional shaping function from
BorrowedTorch.ShapingFunctions, DiscreteAnimationFrame<T> sets a value at a given time. Started, an animation runs
with the UI's updates: Start adds it to the UI's animations (AddAnimation does the same without starting it), and
Stop takes it out, back at its start (the values it set stay). It plays on the time line of BorrowedTorch.Animations
(AnimationTimeline), the one the engine's and the cameras' animations play on, and blends with its AnimationValues.
var slideIn = new Animation<Margin>(400, AnimationRepeatType.None, autoReverse: false, deleteOnComplete: true);
slideIn.AddFrame(new SmoothAnimationFrame<Margin>((-300, 20), (20, 20), 400, shapingFunction: new CubicEaseOut()));
slideIn.AddDependencyProperty(panel.MarginDP);
var pulse = new Animation<Color>(600, AnimationRepeatType.Infinite, autoReverse: true, deleteOnComplete: false);
pulse.AddFrame(new SmoothAnimationFrame<Color>(Color.White, Color.Yellow, 600));
pulse.AddDependencyProperty(hintLabel.ForegroundColorDP);
// a property that is no dependency property, set through its setter
var zoom = new Animation<float>(300);
zoom.AddFrame(new SmoothAnimationFrame<float>(1f, 1.5f, 300));
zoom.AddTarget(map, value => map.Zoom = value);
slideIn.Start();
pulse.Start();
zoom.Start();
// pulse.Pause(); pulse.Reset(); pulse.Stop();
A smooth frame blends what BorrowedTorch.Animations blends by itself - int, long, float, double, Vector2,
Vector3, Vector4, Color, Point, Rectangle and Quaternion (a slerp), whole numbers rounded to the nearest -
and Margin, side by side; AnimationValues.Use<T> makes another type known to every frame. Any other type switches
from From to To at the frame's end, unless the frame is given a blend of its own:
new SmoothAnimationFrame<Matrix>(Matrix.Identity, Matrix.CreateRotationZ(1f), 500) { Blend = Matrix.Lerp };
A value an animation sets counts as set by hand (as by code): it outweighs the element's styles, and stays when the animation is done.
Seek(positionMs) puts an animation at a moment of its time line and gives its targets the values there (a not running
one is paused there, Start goes on from it), and PositionMs tells where it is: for a tool scrubbing through it.
Drag and drop
DragType.DragOnly moves the element (or its DragTarget) with the mouse by changing its margin,
DragType.DragAndDrop shows a DragAndDropRepresentation under the cursor and asks the element under the
mouse whether a drop is allowed (IsDropAllowedPredicate), raising OnDrop or OnDropDenied.
var card = new Image("card")
{
Source = cardTexture,
DesiredWidth = 64,
DesiredHeight = 96,
DragType = DragType.DragAndDrop,
DragAndDropRepresentation = new DragAndDropRepresentation { UseTargetAppearance = true, Transparency = 0.5f }
};
var slot = new Border("slot") { DesiredWidth = 70, DesiredHeight = 102, Thickness = 2 };
slot.IsDropAllowedPredicate = dragged => dragged is Image;
slot.OnDrop += (dragged, destination) => PlaceCard(dragged, destination);
slot.OnDropDenied += (dragged, destination) => Console.WriteLine("not here");
// window title bars use DragOnly to move the whole window:
titleBar.DragType = DragType.DragOnly;
titleBar.DragTarget = window;
Debug helpers
BaseElement.ShowStateTint = true tints hovered / pressed / drop target elements, and per element
ShowHitRectangle / ShowActualSizeRectangle (with ...Diagonals and ...Color) outline the layout.
Grid.ShowLayout draws the cell grid.
Markup
The BorrowedTorch.UI.Markup package builds element trees from XML, so a UI can be written as data instead of code: elements by type name, properties as attributes, items and content as child elements, events by handler name and bindings to a view model. It has a repository of its own.
<Ui>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Name="play" Text="Play" DesiredWidth="200" DesiredHeight="40" OnClick="StartGame" />
</StackPanel>
</Ui>
Demo
Demo/BorrowedTorch.UI.Demo is a MonoGame (DesktopGL) application that shows every element on one screen:
buttons, check boxes and radio buttons, sliders, an animated progress bar, a combo box, windows (normal and
modal), drag and drop, a list box, rich text, text editing, a scrollable container, border and images, the
tree view, a view port with custom drawing and a tab control. Its source doubles as a larger usage example,
including general styles for a dark theme.
dotnet run --project Demo/BorrowedTorch.UI.Demo
With --screenshot <file> [--frames <n>] the demo renders the given number of frames, saves the back buffer
as a PNG and exits, which is handy to check the rendering without clicking through it:
dotnet run --project Demo/BorrowedTorch.UI.Demo -- --screenshot demo.png --frames 90
Building and testing
dotnet build BorrowedTorch.UI.slnx
dotnet test BorrowedTorch.UI.slnx
The tests in Tests/BorrowedTorch.UI.Tests cover the dependency properties, bindings, timers, animations, styles
and the layout of the elements. They run without a GraphicsDevice, so texture generation and input handling
are not covered by them; use the demo's screenshot mode for those.
Changelog
2.6.1
- Depends on
BorrowedTorch.Animations1.1.0 andBorrowedTorch.MonoInput2.2.0 instead of 1.0.0 and 2.1.0. No API changes.
2.6.0
- Compiled against MonoGame 3.8.1.303 instead of 3.8.0.1641, as every BorrowedTorch library that does not need the
compute fork now is. Games already needed 3.8.1 for
BorrowedTorch.MonoInput; what no longer loads it is the oldMonoGame.Framework.Compute.WindowsDX.NoMemoryLeakfork (assembly version 3.8.1.1). No API changes. - The color picker's palette eases between hue stops with MonoGame's
MathHelper.SmoothStepinstead of a copy of it. The colors are unchanged. No public API changes.
2.5.1
- A font file's glyph atlas pages are 1024 x 1024 (4 MB) instead of 2048 x 2048 (16 MB) at UI scales up to 100 %, and another page is added when one is full; above 100 % they stay 2048 x 2048. A single glyph has to fit a page, which holds font sizes up to about 400 units at 100 %.
2.5.0
- Animations play on
BorrowedTorch.Animations, its time line and its blends: smooth frames blendlong,Vector3,Vector4andQuaternionas well, and any type made known byAnimationValues.Use. Whole numbers and colours are blended in double precision rather than single, so a value within a hair of a half can round the other way.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0-windows10.0.19041 is compatible. |
-
net10.0-windows10.0.19041
- BorrowedTorch.Animations (>= 1.1.0)
- BorrowedTorch.MonoInput (>= 2.2.0)
- BorrowedTorch.ShapingFunctions (>= 1.6.1)
- FontStashSharp.MonoGame (>= 1.6.2)
NuGet packages (2)
Showing the top 2 NuGet packages that depend on BorrowedTorch.UI:
| Package | Downloads |
|---|---|
|
BorrowedTorch.UI.Markup
Builds BorrowedTorch.UI element trees from XML markup: elements by type name, their properties as attributes, items and content as child elements, styles and other objects as property elements, events by handler name, bindings to a data context, style dictionaries of keyed and general styles, animations in steps started on load or by an element's event and stopped by one, files included in others, and where each element is written. For UI written as data, loaded by a game at run time and edited live in a tool. |
|
|
BorrowedTorch.Engine
Kindling, Borrowed Torch's game engine: what a game's own code builds against - its features registering components, systems, keys and UI handlers - for the Kindling editor and player to run |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 2.6.1 | 62 | 11/18/2026 |
| 2.6.0 | 63 | 11/18/2026 |
| 2.5.1 | 151 | 11/13/2026 |
| 2.5.0 | 98 | 11/9/2026 |
| 2.4.0 | 108 | 11/1/2026 |
| 2.3.0 | 99 | 11/1/2026 |
| 2.2.0 | 127 | 11/1/2026 |
| 2.1.0 | 122 | 10/31/2026 |
| 2.0.0 | 121 | 10/31/2026 |
| 1.6.1 | 157 | 10/30/2026 |
| 1.6.0 | 98 | 10/30/2026 |
| 1.5.0 | 97 | 10/30/2026 |
| 1.4.0 | 110 | 10/23/2026 |
| 1.3.5 | 103 | 10/23/2026 |
| 1.3.3 | 108 | 10/23/2026 |
| 1.3.2 | 103 | 10/22/2026 |
| 1.3.1 | 102 | 10/22/2026 |
| 1.3.0 | 102 | 10/22/2026 |
| 1.2.2 | 95 | 10/22/2026 |
| 1.2.1 | 96 | 10/22/2026 |