Color legend plain property dependency property method event
BorrowedTorch.UI is the UI framework of Kindling, built for MonoGame. You build the UI from elements (labels, buttons,
lists, windows and more) arranged in a tree. Elements are laid out the way WPF lays them out, with margins,
alignments and sizes that are fixed, stretched or fitted to their content. Every property can be set in code, by a
style, or bound to a view model, and the whole tree is drawn with one SpriteBatch.
These pages cover the library from setup to every public type:
| Page | What it covers |
|---|---|
| Quick start guide (this page) | Installing, creating the UI in a game, sharing the mouse and keys with the game, display scaling, how sizes and alignment work, a complete pause menu |
| Base element | What every element has: size, appearance, items, mouse, keyboard, resizing, and writing your own element |
| Layout elements | Stack panels, grids, scrolling, borders, separators, windows and tabs |
| Controls | Buttons, check boxes, sliders, progress bars, tooltips and the color picker |
| Lists and menus | List boxes, combo boxes, tree views and context menus |
| Text | Labels, rich text boxes, text input and fonts |
| Images and drawing | Images, stencils, view ports for your own drawing, and drag and drop |
| Styles, bindings and animation | Styles, mouse cursors, default settings, dependency properties, view model bindings and animations |
| Markup | The BorrowedTorch.UI.Markup package: elements, properties, items, events, bindings, styles and animations written as XML, in files that include others |
| Glossary | Every element with its properties and methods in alphabetical order, one page per element |
Screenshots on these pages are real renders of the snippets next to them, drawn with the theme shown on the styles page.
Installing
Add the package to your MonoGame project:
dotnet add package BorrowedTorch.UI
| Requirement | Version |
|---|---|
| .NET | 10, Windows (net10.0-windows10.0.19041.0, the text boxes use the Windows clipboard) |
| MonoGame | 3.8.1 or later, DesktopGL or WindowsDX: your game references the platform package, the UI doesn’t pick one for you |
| Input | BorrowedTorch.MonoInput 2.1.0, installed with the UI |
The UI is built against MonoGame 3.8.0, and MonoInput against 3.8.1. .NET loads a library next to the MonoGame it was built against or a newer one, so both run on every MonoGame release from 3.8.1 on.
The package also brings the default font (UbuntuMono). It is copied to Content/Fonts next to your executable, where
the UI finds it.
Setting up the UI
Create the UI once the GraphicsDevice exists, give it the game window, and call Update and Draw every frame. The
UI takes care of the window by itself:
- Text and keys. Typed text and key presses come from the window’s
TextInputandKeyDownevents. - Size. At the start of every
Update, the UI compares the back buffer with the size it saw last. When the window was resized, or the game changed the back buffer, it lays itself out over the new size.
Disposing the UI unsubscribes it from the window. One thing stays with your game:
- Input. The game polls the input. Call
KeyboardManager.Update()andMouseManager.Update()from BorrowedTorch.MonoInput once per frame, before the UI’sUpdate. The UI reads the same managers, so polling them a second time in a frame would lose presses.
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)
{
ExceptionHandler = e => Console.Error.WriteLine(e)
};
// build the UI here, see "Your first elements" below
}
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.Black);
_ui.Draw();
base.Draw(gameTime);
}
protected override void UnloadContent()
{
_ui.Dispose();
_spriteBatch.Dispose();
}
}
The framework keeps its state in static fields, so only one BorrowedTorchUI exists at a time. Creating a second one
throws: dispose the first one before. Disposing the UI detaches the elements you added to the root but doesn’t
dispose them, so dispose the ones that hold resources yourself.
Two cases need more than the window:
- A UI drawn into a render target of its own size. Set
FollowsBackBuffertofalseand give the size withApplyGameWindowSize. With following on, a size you give stays until the back buffer changes. When the target is shown scaled or moved, tell the UI where withShownAt, so it reads the mouse there (see drawing into a render target). - A UI hosted outside a game window, such as a WPF editor or a test. Pass your own
ITextInputEventsinstead of the window.GameWindowTextInputEventsis the adapter the window constructor uses, if you need one by hand. The mouse and the keys still come from MonoInput’s managers, whose polling reads the game window. Give them the state your host tracks instead, withKeyboardManager.Update(keyboardState)andMouseManager.Update(mouseState), once per frame before the UI’sUpdate(see feeding your own state). The cursors the elements ask for go through MonoGame’sMouse.SetCursor, which needs the game window too and throws without one: giveMouseCursorHandleryour own way of showing aMouseCursor, ornullto show none (see showing the cursors).
Drawing into a render target
The UI draws into the render target that is set when Draw is called. A few elements draw pictures of their own
into render targets of their own: a stencil its scaled textures, a
drag and drop representation its picture of the dragged element, a
combo box its picture of the chosen row. Each sets back the render targets that were set
before (before 2.3.0, the back buffer), so a UI drawn into a target of yours goes on drawing into it.
A tool that previews a game’s UI at the game’s resolution draws it into a target of that size and shows the target
scaled, inside its own window. The mouse is still read in the window’s device pixels, so give the UI the rectangle
the target is shown in with ShownAt, in those pixels:
// the game's 1920 x 1080 UI, shown at half its size 100 by 50 pixels into the tool's window
var target = new RenderTarget2D(GraphicsDevice, 1920, 1080);
_ui.FollowsBackBuffer = false;
_ui.ApplyGameWindowSize(1920, 1080);
_ui.ShownAt = new Rectangle(100, 50, 960, 540);
// every frame: the UI into its target, then the target where ShownAt says
GraphicsDevice.SetRenderTarget(target);
GraphicsDevice.Clear(Color.Black);
_ui.Draw();
GraphicsDevice.SetRenderTarget(null);
_spriteBatch.Begin();
_spriteBatch.Draw(target, _ui.ShownAt.Value, Color.White);
_spriteBatch.End();
The mouse is then read through the rectangle: a position in it is mapped onto the UI’s screen, so the window pixel
(579, 319) is the screen’s (959, 539) above, and a position outside of it is outside of the screen, over no element.
Moves and the mouse positions of the events are mapped the same way. MousePosition gives the mouse as the
elements read it, in logical units, for a tool that works over the UI with the mouse. While ShownAt is null, the
default, or a rectangle without a size, the mouse is read as it is.
BorrowedTorchUI
Names are colored by what they are: a plain property, a method or an event.
| Member | Description |
|---|---|
BorrowedTorchUI(GraphicsDevice graphicsDevice, ContentManager contentManager, SpriteBatch spriteBatch, GameWindow window) |
Creates the UI over the back buffer’s size, with the text and keys of the window. The sprite batch is the one the UI draws with; the content manager loads the textures named by TexturesPath. Disposing the UI unsubscribes from the window. |
BorrowedTorchUI(GraphicsDevice graphicsDevice, ContentManager contentManager, SpriteBatch spriteBatch, ITextInputEvents textInputEvents) |
The same, with the text and keys of a source of your own, for a UI hosted outside a game window. The UI doesn’t dispose the source. |
RootElement |
Read-only. The element at the top of the tree, the size of the screen. See the root element. |
AddElementToRoot(BaseElement element) |
Adds an element to the root. |
GetElementByName(string name) |
Finds an element anywhere in the tree by the name given to its constructor, null if there is none. |
GetElementByName<T>(string name) |
The same, null also when the element is not a T. |
Update(GameTime gameTime) |
Runs timers and animations, lays out what changed, and handles the mouse. Poll the input before it. |
Draw() |
Draws the whole tree with the sprite batch, beginning and ending it itself. |
HasMouse |
Read-only. Whether the UI has the mouse: it is over an element that takes the mouse (the root doesn’t count), the buttons pressed on an element are still held, or a modal window is shown. Buttons pressed where no element takes the mouse are the game’s until they are released, also over elements. Worked out from the last update’s layout, so read it after Update. See sharing the mouse and keys. |
HasKeyboard |
Read-only. Whether an element has the keyboard. |
FocusedElement |
Read-only. The element that has the keyboard, null when none has it. |
ElementAt(Point position) |
The element the mouse would be over at a position in logical units, by the rules the UI hovers by, without hovering anything. The root where nothing else takes the mouse, null outside of the screen. |
ElementUnderMouse |
Read-only. ElementAt where the mouse is (MousePosition). |
MousePosition |
Read-only. Where the mouse is, in logical units and through ShownAt: the position the elements read, outside of the screen while the mouse is outside of it. |
FollowsBackBuffer |
Whether the UI takes the back buffer’s size by itself, at the start of every Update. On by default. Turn it off for a UI drawn into a render target of its own size. Turned on again, it takes the back buffer’s size at the next update. |
ApplyGameWindowSize(int width, int height) |
Lays the UI out over a screen size in device pixels. A size of 0, such as a minimized window’s, is ignored. With FollowsBackBuffer on, the size stays until the back buffer changes. |
ShownAt |
The rectangle the UI’s screen is shown in, in device pixels of the window the mouse is read in, for a UI drawn into a render target of its own size and shown scaled or moved: the mouse is read through it (see drawing into a render target). null by default: the screen is shown as it is drawn. A rectangle without a size counts as null. |
Scale |
How large one logical unit is on screen, see display scaling. Between MinScale (0.25) and MaxScale (8). |
FollowsDisplayScale |
Whether Scale follows the display scale of the window’s monitor, times DisplayScaleFactor. Turned on, it sets the scale at once and then follows the window to other monitors. A scale set by hand stays until the DPI changes. Off by default. Needs the window constructor, otherwise turning it on throws. |
DisplayScaleFactor |
What the display scale is multiplied with while following: a UI size setting of the game. 1 by default, a positive number. Set while following, it applies at once. |
DrawTransform |
Read-only. The matrix the UI draws with. Draw code that begins its own sprite batch inside the UI passes it to draw in logical units. |
ExceptionHandler |
Gets the exceptions thrown inside Update, Draw and the handling of text input. Without a handler they are rethrown. |
AddAnimation(BaseAnimation animation) |
Starts updating an animation, which plays once it is started. Animation.Start adds it as well, so this is needed only for one you start later. See animations. |
RemoveAnimation(BaseAnimation animation) |
Stops updating an animation. It keeps its state, and adding it again continues it. |
SetDefaultMouseCursorsSet(MouseCursorsSet mouseCursorsSet) |
Sets the cursors every element uses unless it has its own, see mouse cursors. |
MouseCursorHandler |
Shows the cursors the elements ask for: MonoGame’s Mouse.SetCursor by default. A UI hosted outside a game window gives its own way, or null to show none. See showing the cursors. |
Dispose() |
Disposes the root and forgets the shared state, so a new UI can be created. |
ITextInputEvents
The source of typed text and key presses, for a UI hosted outside a game window.
| Event | Description |
|---|---|
OnTextInput |
EventHandler<TextInputEventArgs>: a typed character, sent to the element that has the keyboard. |
OnKeyDown |
EventHandler<InputKeyEventArgs>: a pressed key, sent to the element that has the keyboard and then up to its parents until one handles it. |
GameWindowTextInputEvents
An ITextInputEvents that forwards a MonoGame window’s events. The window constructor of BorrowedTorchUI creates and
disposes one itself.
| Member | Description |
|---|---|
GameWindowTextInputEvents(GameWindow window) |
Subscribes to the window’s TextInput and KeyDown events. |
Dispose() |
Unsubscribes from the window. |
Sharing the mouse and keys with the game
The game reads the same mouse and keys as the UI. So that 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:
protected override void Update(GameTime gameTime)
{
KeyboardManager.Update();
MouseManager.Update();
_ui.Update(gameTime);
// HandleWorldClicks and HandleMovementKeys stand for the game's own input code
if (!_ui.HasMouse) HandleWorldClicks();
if (!_ui.HasKeyboard) HandleMovementKeys();
base.Update(gameTime);
}
HasMouse is true while:
- The mouse is over an element that takes the mouse. The root, where no other element is, doesn’t count.
- The buttons pressed on an element are held: a drag, a resize, a slider pulled past its end.
- A modal window is shown.
The first rule doesn’t hold for a press that began where no element takes the mouse. That press is the game’s: until
its buttons are released HasMouse stays false, also while the mouse passes over elements, which aren’t hovered
meanwhile. So a camera dragged across a panel goes on turning.
It is worked out when it is read, from the layout of the last update. An element stretched over the screen, such as a
panel that draws a background, takes the mouse everywhere unless its HitTest is off. A Grid, a StackPanel and a
Label have it off by default.
HasKeyboard is true while an element has the keyboard, and FocusedElement says which one. A mouse
press outside of that element takes the keyboard away from it, a press where no element takes the mouse included, so a
click into the game ends the typing.
Finding the element at a point
ElementAt(Point position) finds the element the mouse would be over at a position in logical units, without
hovering anything. It goes by the rules the UI hovers by (see mouse and states):
- The open context menu and the open drop-down come first, then the tree from the top down: windows above their
siblings, children by
ZIndex. - Only visible elements that take the mouse count, and only where they aren’t cropped away.
- While a modal window is shown, only its elements and the root around it count.
Where nothing else takes the mouse it returns the root, and outside of the screen null. ElementUnderMouse is the
element at the mouse, read where the elements read it (MousePosition). The element found can be a part of a
control, such as a list’s row or a slider’s thumb (IsPart tells a part from what you gave the control, see
inspecting elements), so walk up its Parents to the element you want:
// the window under the mouse, null where there is none
var element = _ui.ElementUnderMouse;
while (element != null && element is not Window) element = element.Parent;
var window = (Window)element;
Your first elements
Every element has a constructor taking an optional name. Set its properties, subscribe to its events and add it to the
root (or to another element). The snippets on these pages call the UI ui; in the game above it is _ui.
var title = new Label("title")
{
Text = "Borrowed Torch",
FontSize = 24,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Margin = (16, 16)
};
var play = new Button("play")
{
Text = "Play",
DesiredWidth = 140,
DesiredHeight = 36,
Margin = (16, 58)
};
play.OnClick += (sender, e) => Console.WriteLine("Play pressed");
ui.AddElementToRoot(title);
ui.AddElementToRoot(play);
Sizes and alignment
An element’s size along each side comes from three settings:
- A fixed size.
DesiredWidthandDesiredHeightabove 0 fix it. - Stretched. Without a size, an element whose
HorizontalAlignmentorVerticalAlignmentisStretchtakes the space its parent gives it, less its margins.Stretchis the default alignment of most elements. - Fitted to its content. Without a size and with any other alignment, the element is as large as its content.
MinWidth, MinHeight, MaxWidth and MaxHeight limit the result, with 0 meaning no limit.
In a parent that fits its content, such as a stack panel, an auto-sized grid row or a fitted window body, a stretched
child counts with the size of its own content, as in WPF. A label left at the default Stretch has its text’s height
in a stack panel, 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.
Give the parent a MaxWidth to make it wrap.
// one look for every label: centered text on a brown fill; no text margin,
// so a fitted label hugs its text
Label Swatch(string text) => new()
{
Text = text,
TextAlignment = TextAlignment.Center,
VerticalTextAlignment = VerticalTextAlignment.Center,
BackgroundColor = new Color(110, 82, 48)
};
// four identical framed areas of 240 x 90, each holding one label inside its frame
void Area(int left, int top, Label label) => ui.AddElementToRoot(new Border
{
DesiredWidth = 240,
DesiredHeight = 90,
HorizontalAlignment = HorizontalAlignment.Left,
VerticalAlignment = VerticalAlignment.Top,
Margin = (left, top),
Thickness = 1,
ForegroundColor = new Color(90, 70, 48),
BackgroundColor = new Color(30, 24, 18),
Content = label
});
// a fixed size, at the top left of its area
var fixedSize = Swatch("120 x 40");
fixedSize.DesiredWidth = 120;
fixedSize.DesiredHeight = 40;
fixedSize.HorizontalAlignment = HorizontalAlignment.Left;
fixedSize.VerticalAlignment = VerticalAlignment.Top;
Area(12, 12, fixedSize);
// fitted to its text: no size, not stretched
var fitted = Swatch("Fits its text");
fitted.HorizontalAlignment = HorizontalAlignment.Left;
fitted.VerticalAlignment = VerticalAlignment.Top;
Area(268, 12, fitted);
// stretched across the width, as high as its text
var across = Swatch("Stretched across");
across.VerticalAlignment = VerticalAlignment.Top;
Area(12, 118, across);
// stretched both ways: no size and the default alignments
Area(268, 118, Swatch("Stretched both ways"));
The alignments place an element inside the space its parent gives it: Left, Center, Right or Stretch
horizontally, Top, Center, Bottom or Stretch vertically.
Label Badge(string text, HorizontalAlignment horizontal, VerticalAlignment vertical) =>
new()
{
Text = text,
TextMargin = (10, 6, 10, 6),
HorizontalAlignment = horizontal,
VerticalAlignment = vertical,
BackgroundColor = new Color(58, 44, 30),
Margin = 12
};
ui.AddElementToRoot(Badge("Left, Top",
HorizontalAlignment.Left, VerticalAlignment.Top));
ui.AddElementToRoot(Badge("Center, Top",
HorizontalAlignment.Center, VerticalAlignment.Top));
ui.AddElementToRoot(Badge("Right, Top",
HorizontalAlignment.Right, VerticalAlignment.Top));
ui.AddElementToRoot(Badge("Left, Center",
HorizontalAlignment.Left, VerticalAlignment.Center));
ui.AddElementToRoot(Badge("Center, Center",
HorizontalAlignment.Center, VerticalAlignment.Center));
ui.AddElementToRoot(Badge("Right, Center",
HorizontalAlignment.Right, VerticalAlignment.Center));
ui.AddElementToRoot(Badge("Left, Bottom",
HorizontalAlignment.Left, VerticalAlignment.Bottom));
ui.AddElementToRoot(Badge("Center, Bottom",
HorizontalAlignment.Center, VerticalAlignment.Bottom));
ui.AddElementToRoot(Badge("Right, Bottom",
HorizontalAlignment.Right, VerticalAlignment.Bottom));
Margins
Margin keeps an element away from the edges of its slot. It converts 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
A margin pushes the element away from the side it is aligned to. A parent that fits its content counts a child’s
margin only on that side: the left and top margins for Left and Top, the right and bottom ones for Right and
Bottom, both for Center. So in a horizontal stack panel, put the gap between two items on the left margin of the
second one, not on the right margin of the first.
Units
Sizes, margins, positions and font sizes are in logical units: one unit is one pixel at a display scale of 100 %. The
layout runs in two passes whenever something changed: measure finds every element’s size, then arrange gives each its
final size (ActualWidth, ActualHeight) and position (Location, in screen units). The
base element page explains the passes for custom elements.
Display scaling
On a display scaled to 150 %, Windows stretches the window of a game that isn’t DPI aware, and everything comes out blurred. Such a game is also told 96 DPI on every monitor. 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. The UI is then drawn at the display’s full resolution, one and a half times larger.
// 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. Every 30 updates it reads the monitor’s DPI again, and when the window moves
to a monitor with another scale, the UI takes that scale. The window keeps its pixels, and the UI fills them. A scale you
set by hand stays until the DPI changes. Following needs the constructor that takes the game window.
The layout doesn’t change with the scale. Sizes, margins, positions, font sizes and the mouse positions in events
all stay in logical units; only the drawing, the clipping and the reading of the mouse are scaled, and fonts are
rasterized for the scale. The screen size stays in device pixels, whether it is the back buffer’s or one given to
ApplyGameWindowSize, and the root covers it in logical units: at 150 % a 1920 x 1200 back buffer is a 1280 x 800
layout. The screenshots on these pages are rendered at a scale of 2.
DisplayScale
Reads the Windows display scale of the monitor a window is on. Without the awareness call, Windows reports 96 DPI.
| Member | Description |
|---|---|
DefaultDpi |
96, the DPI of a monitor at 100 %. |
DeclarePerMonitorAwareness() |
Declares the process per-monitor DPI aware. Call it before the game creates its window. Returns false when Windows doesn’t accept it: the awareness was declared already, by an application manifest or an earlier call, or Windows is older than Windows 10 1703. |
DpiOf(GameWindow window) |
The DPI of the monitor under the middle of the window’s client area. 96 when it can’t be read. |
DpiOf(Rectangle screenBounds) |
The same for a rectangle in screen coordinates, using the nearest monitor when none is under it. |
ScaleOf(GameWindow window) |
The display scale as a UI scale: the DPI divided by 96, so 1.5 at 150 %. |
Some limits come with scaling:
- 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.
- A
FontSystemgiven by hand keeps the resolution it was created with. - Draw code that begins its own sprite batch inside the UI passes
DrawTransform. A view port draws in device pixels.
A pause menu
A modal window over the game, with three buttons in a stack panel. While it is open, the rest of the UI is shaded and gets no mouse input, and Escape closes it.
var menu = new StackPanel("pauseButtons")
{
Orientation = Orientation.Vertical,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center
};
var resume = new Button("resume")
{
Text = "Resume",
DesiredWidth = 200,
DesiredHeight = 36
};
var settings = new Button("settings")
{
Text = "Settings",
DesiredWidth = 200,
DesiredHeight = 36,
Margin = (0, 10)
};
var quit = new Button("quit")
{
Text = "Quit to menu",
DesiredWidth = 200,
DesiredHeight = 36,
Margin = (0, 10)
};
menu.AddItemsRange([resume, settings, quit]);
var pauseWindow = new Window("pause")
{
DesiredWidth = 260,
DesiredHeight = 210,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
IsModal = true,
Content = menu
};
var titleBar = (DefaultWindowTitleBar)pauseWindow.TitleBar;
titleBar.Title.Text = "Paused";
titleBar.CloseButton.Text = "x";
// lit like the other buttons: a close button is flat on the bar until hovered
titleBar.CloseButton.NormalColor = new Color(168, 131, 74);
resume.OnClick += (sender, e) => pauseWindow.Hide();
quit.OnClick += (sender, e) => Console.WriteLine("Back to the main menu");
// Escape closes the menu while anything in it has the keyboard
pauseWindow.OnKeyDown += (sender, e) =>
{
if (e.Key != Keys.Escape) return;
pauseWindow.Hide();
e.Handled = true;
};
ui.AddElementToRoot(pauseWindow);
pauseWindow.Show();
The layout elements page has more on windows, and the base element page on how keys travel up to the window.