Color legend plain property dependency property method event
BorrowedTorch.UI.Markup builds elements from XML markup, so a UI can be written as data instead of code: loaded by the game at run time, or edited live in a tool. A markup names the UI’s elements by their type names and sets the same properties code sets. Styles can be written as markup too, in style dictionaries, a markup can include other files, and a UI can animate the properties of its elements. It is a package of its own next to BorrowedTorch.UI, with a repository of its own.
<Ui>
<StackPanel Name="menu" Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Name="newGame" Text="New game" DesiredWidth="200" DesiredHeight="40" OnClick="StartNewGame" />
<Button Name="options" Text="Options" DesiredWidth="200" DesiredHeight="40" Margin="0, 8" />
<Label Text="{Binding PlayerName}" Margin="0, 8" />
</StackPanel>
</Ui>
using BorrowedTorch.UI.Markup;
// this object has the StartNewGame method, settings has the PlayerName property
var context = new MarkupContext { Handlers = this, DataContext = settings };
foreach (var element in UiMarkup.LoadFile("UI/MainMenu.btui", context))
ui.AddElementToRoot(element);
Installing
dotnet add package BorrowedTorch.UI.Markup
| Requirement | Version |
|---|---|
| UI | BorrowedTorch.UI 2.2.0 or later, installed with the markup |
| .NET | 10, Windows (net10.0-windows10.0.19041.0), as the UI |
The types are in the BorrowedTorch.UI.Markup namespace. This page covers version 1.7.0: 1.5.0 added
reading values as the markup does, 1.6.0 animations, and 1.7.0 their
steps, StopOn and seeking. Each version asks for the BorrowedTorch.UI it is built
against: 2.2.0 for 1.7.0, 2.1.0 for 1.6.0, 2.0.0 for 1.5.0, and 1.6.1 for the ones before.
Loading markup
UiMarkup.Load reads a markup from a string, and LoadFile from a file (any path File.ReadAllText
takes; any extension does, these pages use .btui). Both return the elements written under <Ui>, in the order they
are written, not added anywhere yet: add them to the root with
AddElementToRoot or to an element of your own. An element you don’t add stays yours to dispose.
The elements are made as code would make them, with their constructors. So load a markup on the thread that updates
the UI, once the UI exists: an image’s Source loads its texture through the UI’s ContentManager while the markup
is read.
LoadDocument and LoadDocumentFile return the same elements in a MarkupDocument, which
remembers every element the markup made. Disposing the document disposes all of them, the items and contents of its
panels included, which disposing a panel only detaches. That is the way to take a whole UI away: a screen that is left,
or a markup loaded again in its place, as a tool does after an edit. A document also has the markup’s
elements as written, with where each one is, and its animations, which
disposing it stops.
_menu?.Dispose();
_menu = UiMarkup.LoadDocumentFile("UI/MainMenu.btui", context);
foreach (var element in _menu.Elements)
ui.AddElementToRoot(element);
A MarkupContext gives a markup what it reaches besides the UI’s own types: the object whose methods handle
its events, the object its bindings read, the style dictionaries its styles come from, where it
finds the files it includes, and types and converters of your own.
A markup that uses none of them needs no context.
UiMarkup
A static class.
| Method | Description |
|---|---|
Load(string markup, MarkupContext context = null) |
Returns the elements under <Ui> (an IReadOnlyList<BaseElement>), in the order they are written, not added anywhere. Throws a MarkupException for a markup that can’t be read, an ArgumentNullException for a null markup. |
LoadFile(string path, MarkupContext context = null) |
Load of the text of a file, read through the context’s ReadFile; its includes are found from its directory. The errors of reading the file itself, such as a missing file, are thrown as they are. |
LoadDocument(string markup, MarkupContext context = null) |
Load, returning a MarkupDocument that keeps every element the markup made, to dispose them all at once. |
LoadDocumentFile(string path, MarkupContext context = null) |
LoadDocument of the text of a file, read as LoadFile reads it. |
LoadStyles(string markup, MarkupContext context = null) |
Reads a style dictionary, a markup whose root is <Styles>, into a StyleDictionary. Throws a MarkupException for one that can’t be read. |
LoadStylesFile(string path, MarkupContext context = null) |
LoadStyles of the text of a file, read as LoadFile reads it. |
IsStyleDictionary(string markup) |
Whether a markup’s root is <Styles> (for LoadStyles) rather than <Ui> (for Load), for a tool that takes both. It reads up to the root only; a markup that isn’t well formed that far is no dictionary. |
TryReadColor(string text, out Color color) |
Reads a text as a Color property’s value is read, and returns whether it could. For a tool that shows the colors of a markup. |
ReadValue(string text, Type type, MarkupContext context = null) |
Reads a text as an attribute setting a property of the type is read, the context’s converters first, and returns the value. A text that can’t be read throws a FormatException with the reason a markup gives for it. For a tool that sets properties from text. |
CanReadValue(Type type, MarkupContext context = null) |
Whether a value of the type is written as text, so that ReadValue reads it. A type that isn’t is given in a property element. |
MarkupDocument
A sealed class, IDisposable.
| Property | Type | Description |
|---|---|---|
Elements |
IReadOnlyList<BaseElement> |
Read-only. The elements under <Ui>, in the order they are written. |
Nodes |
IReadOnlyList<MarkupNode> |
Read-only. The markup’s elements as written, in a tree: the ones under <Ui>, with the elements written in them, an include holding the elements of its UI. |
Animations |
IReadOnlyList<MarkupAnimation> |
Read-only. The animations of the markup’s <Ui.Animations> and of the UIs it includes. Empty once the document is disposed. |
| Method | Description |
|---|---|
NodeOf(BaseElement element) |
The node of an element the markup has, null for one it doesn’t, such as a part a control made for itself (a slider’s thumb): walk up its parents to the element written. |
NodeAt(string position) |
The node at a Position, null where there is none. |
FindAnimation(string key) |
The animation of the key (left.pulse for one of a UI included with Name="left"), null for none. |
StartLoadAnimations() |
Starts the animations whose StartOn has Load, from their beginnings: what a load does, unless the context’s StartsLoadAnimations is false. |
Dispose() |
Stops the markup’s animations, then disposes every element the markup made, the items and contents of its panels included; a disposed element leaves its parent, the root as well. Elements added to them since are only detached, as a panel’s own items are. |
Writing markup
Elements
The root is <Ui>, with no attributes; it holds the UI’s elements, its own styles and its
animations. Every element in it is one of the UI’s elements by its type name: <Button>,
<StackPanel>, <Grid>, <Window>. The markup knows every public class of the UI that isn’t abstract or generic: the
elements, the styles and the objects they take, such as a MouseCursorsSet.
MarkupContext.AddType adds types of your own.
Name is the element’s Name, given to its constructor (an element’s name never changes). An element
written without one has no name, and GetElementByName doesn’t find it. An element is made with its constructor
taking a name, which every element of the UI that code makes has. The parts the controls make themselves (a list’s
ListBoxItem, a menu’s ContextMenuItem, a tree’s TreeViewItem) have none and can’t be written. XML comments are
fine, and namespace declarations (xmlns) are passed over.
Properties
An attribute sets the property of its name: any public property that can be set, the same ones code sets. Its text is read by the property’s type:
| Type | Written as |
|---|---|
string |
As it is. |
| Numbers | 120, 0.5: a point, whatever the decimal separator of the machine. |
bool |
true, false. |
| Enums | The name of a value, in any case: Center, collapsed. |
Color |
#RRGGBB, #RRGGBBAA, r, g, b or r, g, b, a (0 to 255), or the name of one of Color’s colors: CornflowerBlue. |
Margin |
5 (every side), 10, 20 (left, top), 10, 20, 30 (left, top, right) or 10, 20, 30, 40, as in code. The sides not written are 0. |
Point, Vector2 |
x, y. |
| A type that converts from a string | An image’s Source (SourceData): a content path, loaded through the UI’s ContentManager. |
| A nullable type | An empty or blank text is null, any other is read as the type. |
Any other type can’t be written as text: give it in a property element, or add a
converter of your own to the context. A tool that shows the colors of a markup
reads them as the markup does with UiMarkup.TryReadColor, and any value with
ReadValue.
The text inside an element is its Text: <Label>Score</Label> is <Label Text="Score" />. Giving both is an error.
Reading values in a tool
UiMarkup.ReadValue reads a text as an attribute setting a property of a type is read: the formats of the
table above, the context’s converters first, and a blank text as null for a nullable type. CanReadValue
tells whether a type is written as text at all; a type that isn’t, such as a style, is given in a property element. A
tool that sets an element’s properties from what is typed, such as an editor’s list of an element’s properties, sets
them as a markup would:
void SetTyped(BaseElement element, PropertyInfo property, string typed)
{
// a style or an element is no text: it is given in a property element
if (!UiMarkup.CanReadValue(property.PropertyType, context)) return;
try
{
property.SetValue(element, UiMarkup.ReadValue(typed, property.PropertyType, context));
}
catch (FormatException exception)
{
// Margin: '1, 2, 3, 4, 5' is no all, or left, top[, right[, bottom]]
errorLabel.Text = $"{property.Name}: {exception.Message}";
}
}
A text that can’t be read throws a FormatException whose message is the reason a markup gives for it after the
attribute’s name, so the tool says what a load would. An exception a converter or a type’s own conversion from text
throws (an image’s Source loading its texture) comes inside a FormatException with its message; a converter’s own
FormatException comes as it is. ReadValue reads values only: a {Binding ...}, a {Style ...} or a leading {} is
read as any other text.
Items and content
A child element is an item of the element it is in, added with AddItem: the buttons of a stack
panel, the rows of a list box or a combo box, the elements of a grid’s cells, the top-level items of a tree view. An
element with a Content (a Border, a Button, a
CheckBox, a ToolTip, a
Window) holds one child element instead, its content: put several in a panel. An element
that takes neither, such as a Label or a Slider, refuses child elements.
<Window Name="inventory" DesiredWidth="300" DesiredHeight="240">
<StackPanel Orientation="Vertical">
<Label>Inventory</Label>
<ListBox DesiredWidth="260" DesiredHeight="160">
<Label Text="Rope" />
<Label Text="Lantern" />
</ListBox>
</StackPanel>
</Window>
Property elements
A property whose value is no text, such as an element or a style, is given by a property element, named after the
element and the property: <Button.ToolTip> inside a <Button>. It takes no attributes and holds one value, written
as an element is. A style or another object that is no element sets its properties by attributes too, and its own
objects by property elements; it needs a constructor without parameters. A property element with only text in it
gives that text, for a text too long for an attribute.
<Button Name="save" Text="Save" DesiredWidth="120" DesiredHeight="32">
<Button.ToolTip>
<ToolTip Text="Save the game (Ctrl+S)" />
</Button.ToolTip>
<Button.TextStyle>
<LabelStyle FontSize="18" ForegroundColor="White" />
</Button.TextStyle>
</Button>
Grid columns and rows
A Grid’s Columns and Rows list its column and row definitions, in order: a number is a
fixed size in units, auto an auto size as large as the content, and * or 2* a proportional size, a
share of the space left. They are the three kinds of
AddColumnDefinition and AddRowDefinition. The elements in the grid take their cells by
GridRow, GridColumn and their spans, as in code.
<Grid Columns="200, *" Rows="auto, *">
<Label Text="Title" GridColumnSpan="2" />
<ListBox GridRow="1" />
<Image GridColumn="1" GridRow="1" Source="Textures/Preview" />
</Grid>
Events
An attribute named after an event subscribes a method of the context’s
Handlers: OnClick="StartNewGame" subscribes its StartNewGame. The method can be public or not, and
takes either the event’s parameters, such as (BaseElement sender, MouseClickEventArgs e) for
OnClick, or none.
Without such a method the markup can’t be read, unless the context has a
MissingHandler: then the event calls that instead, with the element, the event’s name and the handler’s
name. A tool shows a markup’s events that way, without the game’s code to handle them. A method that is there but
takes other parameters is still an error.
var context = new MarkupContext
{
MissingHandler = (sender, eventName, handlerName) =>
Console.WriteLine($"{((BaseElement)sender).Name}: {eventName} would call {handlerName}")
};
Bindings
{Binding Name} binds a property to the property Name of the context’s
DataContext, usually a Bindable view model whose changes the
element follows. Mode sets the direction, one of the BindingMode values: {Binding Volume, Mode=TwoWay}.
Without it the binding is OneWay. Path=Volume names the property too.
A binding in markup is the binding code makes with the property’s
Bind (see bindings), so only a dependency property can be bound. It takes
no converter: make a binding that needs one in code. A text that starts with a brace and is no binding starts with
{}, which is left out: Text="{}{not bound}" shows {not bound}.
Styles
Style dictionaries
A style dictionary is a markup whose root is <Styles>, holding styles by their
type names. A style with a Key is named by markups; one without is the general style of its type, one of each type.
BasedOn starts a style as a copy of another of the same type, written before it in the dictionary or in a dictionary
of the context: the copy is made as the dictionary is read, so a later change to the other style doesn’t reach it.
<!-- UI/Theme.btui -->
<Styles>
<ButtonStyle DesiredHeight="36" NormalColor="168, 131, 74" HoverColor="233, 194, 122"
PressedColor="128, 98, 54">
<ButtonStyle.TextStyle>
<LabelStyle ForegroundColor="20, 14, 10" />
</ButtonStyle.TextStyle>
</ButtonStyle>
<ButtonStyle Key="danger" NormalColor="150, 52, 30" HoverColor="242, 140, 40" />
<ButtonStyle Key="bigDanger" BasedOn="danger" DesiredHeight="48" />
<LabelStyle Key="title" FontSize="24" ForegroundColor="233, 194, 122" />
</Styles>
UiMarkup.LoadStylesFile reads it into a StyleDictionary. Its general styles are applied apart, with
ApplyGeneralStyles, and its keys reach the markups loaded with a context it is added to with
AddStyles:
var theme = UiMarkup.LoadStylesFile("UI/Theme.btui");
// the styles without a key: Button.GeneralStyle, for every button of the game
var generalStyles = theme.ApplyGeneralStyles();
// the keys, for the markups loaded with this context
var context = new MarkupContext { Handlers = this }.AddStyles(theme);
Disposing what ApplyGeneralStyles returns puts back the general styles there were before, for a theme that
changes. LoadStyles takes a context too, for style types and converters of your own and for the keys of the
dictionaries loaded before it, which BasedOn can name.
Naming a style
Style="key" gives an element the style of the key as its
StyleOverride, over its general style: the danger button below keeps the general height and text
color, and changes only its colors. {Style key} gives a keyed style to any style property, such as a button’s
TextStyle.
<StackPanel Orientation="Vertical">
<Label Text="Delete the save?" Style="title" />
<Button Text="Delete" Style="danger" OnClick="DeleteSave" />
<Button Text="Keep it" TextStyle="{Style title}" />
</StackPanel>
The elements naming a style share it: a change made to it later, such as
theme.Get<ButtonStyle>("danger").NormalColor = Color.DarkRed, reaches all of them. A key is looked up in the UI’s own
styles first, then in those of the UIs that include it, then in the context’s dictionaries, the one added last first.
A UI’s own styles
A UI can hold styles of its own in <Ui.Styles>, read before its elements wherever it is written. Their keys are found
before the context’s. A style there without a key is given to the UI’s elements of its type that name no style of their
own, as their StyleOverride: unlike a dictionary’s general styles, which every element of the game takes, it reaches
only the elements of this markup.
<Ui>
<Ui.Styles>
<ButtonStyle DesiredWidth="200" />
<LabelStyle Key="hint" FontSize="12" ForegroundColor="Gray" />
</Ui.Styles>
<StackPanel Orientation="Vertical">
<Button Text="Play" />
<Label Text="Press F1 for help" Style="hint" />
</StackPanel>
</Ui>
StyleDictionary
A sealed class.
| Property | Type | Description |
|---|---|---|
Keyed |
IReadOnlyDictionary<string, BaseStyle> |
Read-only. The styles with a key, by their keys. |
General |
IReadOnlyDictionary<Type, BaseStyle> |
Read-only. The styles without a key, by their style types, one each. |
| Method | Description |
|---|---|
Get<T>(string key) |
The style with the key, as its type T. A key that isn’t there throws a KeyNotFoundException, a style of another type an InvalidCastException. |
ApplyGeneralStyles() |
Makes each style without a key the general style of its type (Button.GeneralStyle for a ButtonStyle), which every element of the type takes under its own values. Returns an IDisposable that puts back the general styles there were before, where they are still the dictionary’s: a general style set since stays. |
Including other files
<Include Source="..." /> puts what another file holds in its place, its path relative to the including file’s
directory. Among elements it gives the elements of another UI, as if written there, so a screen is made of parts and a
part used by many screens is written once:
<!-- UI/MainMenu.btui -->
<Ui>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<Include Source="Parts/Header.btui" />
<Button Name="play" Text="Play" DesiredWidth="200" DesiredHeight="40" OnClick="Play" />
<Include Source="Parts/VolumeSlider.btui" Name="music" />
<Include Source="Parts/VolumeSlider.btui" Name="effects" />
</StackPanel>
</Ui>
<!-- UI/Parts/VolumeSlider.btui -->
<Ui>
<StackPanel Orientation="Horizontal" Margin="0, 8">
<Label Name="label" DesiredWidth="80" />
<Slider Name="slider" DesiredWidth="160" DesiredHeight="18" />
</StackPanel>
</Ui>
A Name on the include goes before the names of its elements: the slider of VolumeSlider.btui is music.slider
in one place and effects.slider in the other, found apart with
GetElementByName:
ui.GetElementByName<Label>("music.label").Text = "Music";
ui.GetElementByName<Label>("effects.label").Text = "Effects";
An include where one element is taken, a Content or a property element, gives the one element of its UI. An included
UI looks a key up in its own <Ui.Styles> first, then in the including UI’s, and takes the including UI’s general
styles where it has none of its own.
In a style dictionary or a UI’s <Ui.Styles>, an include gives the styles of another dictionary, as if written there. A
style written after it with the same key, or without a key and of the same type, replaces the included one. A theme is
made of parts that way, and a screen names its own theme without code:
<Ui>
<Ui.Styles>
<Include Source="Theme.btui" />
<ButtonStyle Key="danger" NormalColor="DarkRed" />
</Ui.Styles>
<!-- the screen's elements -->
</Ui>
The theme’s general styles are then the screen’s own, given to its elements only, where
ApplyGeneralStyles gives them to the whole game.
A markup loaded with LoadFile, LoadDocumentFile or LoadStylesFile finds its includes from its file’s
directory; one given as text, from the context’s BaseDirectory (the current directory without one). Every
file, the loaded one and the included ones, is read through the context’s ReadFile, File.ReadAllText
without one: a game whose files are elsewhere, such as in a content package, gives its own, and a tool can follow which
files a markup read.
An include holds nothing and takes a Source and a Name (only a Source among styles). A file that can’t be read, a
file that includes itself, a UI included among styles and a style dictionary included among elements are errors at the
include. An error inside an included file is reported at the include too, with the file, line and column it is at.
Animations
A UI’s <Ui.Animations> takes properties of its elements from a value to another over a time, as code does with the
UI’s animations. Each <Animation> in it animates one property of one element and is
given by its attributes. Here a button pulses from the moment the markup is loaded, grows as the mouse enters it and
shrinks back as the mouse leaves:
<Ui>
<Ui.Animations>
<Animation Key="pulse" Target="play" Property="NormalColor" From="SteelBlue" To="Gold" Duration="600"
Repeat="Forever" AutoReverse="true" Easing="CubicEaseInOut" StartOn="Load" />
<Animation Target="play" Property="DesiredWidth" To="220" Duration="150" StartOn="play.OnMouseEnter" />
<Animation Target="play" Property="DesiredWidth" To="160" Duration="150" StartOn="play.OnMouseLeave" />
</Ui.Animations>
<Button Name="play" Text="Play" DesiredWidth="160" DesiredHeight="40" />
</Ui>
<Ui.Animations> is read once the UI’s elements are made, wherever it is written in <Ui>, so it can come before them
as here. A UI has one at most. It takes no attributes and holds only <Animation>s, which hold nothing but their
steps.
| Attribute | Description |
|---|---|
Target |
The Name of the element whose property it animates, an element of the markup. The elements of an included UI are named with the include’s name before theirs (left.play); the included UI’s own animations name them without it. |
Property |
The property, one that can be read and set, of a type written as text (see properties) or one the context has a converter for. A property with a dependency property (NormalColorDP for NormalColor) is animated through it, any other through its setter (see setter targets). |
From |
The value it starts from. Without one, the value the property has as the animation starts, at each start. |
To |
The value it ends at. |
Duration |
Its time from the one to the other, in milliseconds: a whole number, 0 or more. |
Delay |
The time before it moves, in milliseconds, 0 or more; none without. |
Repeat |
Forever, or a number of runs, 1 or more. One run without. |
AutoReverse |
true: each run goes back to its start after reaching its end. false without. |
Easing |
The curve of its way: a shaping function of BorrowedTorch.ShapingFunctions, which the UI installs, by its class name in any case, such as CubicEaseInOut or BounceEaseOut; one that takes parameters has its defaults. Linear without. |
StartOn |
Load, an element’s event (play.OnMouseEnter), or several of them, comma-separated: Load, play.OnClick. Without one, only code starts it. |
StopOn |
An element’s event, or several, comma-separated: each stops it where it is. |
Key |
Its name for code, which FindAnimation finds. The keys of an included UI have the include’s name before them (left.pulse). |
Target and Property are needed, and so are To and Duration unless it has steps; the others may be
left out. From and To are written as the
property’s attribute is, the context’s converters included. The UI blends the values of int, float, double,
Color, Margin, Point, Vector2 and Rectangle properties along the way; a property of any other type, such as an
enum or a bool, keeps the value it starts from to the end of the time and takes To there.
An animation started on Load starts as the markup is loaded, one started by an event each time its element raises
it. An event is named after its element, the event’s name after the last dot, so the dotted name of an included
element is fine: left.play.OnMouseEnter. Any event of the element does, whatever it passes its handlers, such as a
check box’s OnCheckedUnchecked. A start runs the animation from its beginning, again if it ran before; a
stop leaves it where it is, the property keeping the value it set last.
Starting an animation stops the markup’s other animations of the same property of the same element, wherever they are
written. The two animations of the button’s DesiredWidth take turns that way: a mouse leaving before the button has
grown to 220 shrinks it back from wherever it is, since the second animation has no From.
Steps
An animation goes through several values one after another with <Step>s in place of its own To and Duration.
Each step goes on from where the one before ends, the first from the animation’s From (or the property’s value), to
its own To over its own Duration, after a Delay of its own, eased by its own Easing or else by the
animation’s. The animation’s Delay comes before the first step, and its Repeat and AutoReverse take its steps as
one run. A logo bouncing:
<Animation Key="bounce" Target="logo" Property="Margin" From="0, 40" Repeat="Forever" Easing="CubicEaseOut"
StartOn="Load">
<Step To="0, 10" Duration="300" />
<Step To="0, 40" Duration="300" Easing="CubicEaseIn" />
<Step To="0, 40" Duration="0" Delay="600" />
</Animation>
The logo rises for 300 ms and falls back for 300 ms; the last step, with no time of its own, holds it there for 600 ms
before the next run. A step takes a To and a Duration, which it needs, a Delay and an Easing, and holds
nothing. An animation with steps takes no To or Duration of its own.
Starting and stopping from code
MarkupDocument.Animations lists the animations of the markup and of the UIs it includes, and
FindAnimation finds one by its key. Start runs it from its beginning, Stop stops it where it
is, and IsRunning tells whether it runs. Disposing the document stops them all before it disposes the elements.
var pulse = _menu.FindAnimation("pulse");
// no pulse while the options are open over the menu
pulse.Stop();
// and from its beginning once they are closed
pulse.Start();
Load and LoadFile start the animations too, but give no document to reach them by: load a markup whose
animations code starts, stops or seeks with LoadDocument or LoadDocumentFile.
Animations in a tool
A tool showing a markup as it is written sets its context’s StartsLoadAnimations to false: the animations
started on Load then wait, the elements keeping their values as written, until
StartLoadAnimations starts them, when the tool plays the UI. The events still start theirs.
Seek shows a moment of an animation, for a tool scrubbing through it: the property takes the value the
animation gives it at a position, in milliseconds from its start, kept within 0 and DurationMs, its time line
of one run (its delay, and its steps’ pauses and times). The markup’s other animations of the property stop first. A
running animation goes on from there; one that isn’t running stays there until Start runs it from its beginning.
PositionMs tells where its time line is. Both are its
animation’s.
var context = new MarkupContext { StartsLoadAnimations = false, MissingHandler = (_, _, _) => { } };
var document = UiMarkup.LoadDocumentFile(path, context);
var bounce = document.FindAnimation("bounce");
// a slider of the tool, along the animation's time line
timeline.Max = bounce.DurationMs;
timeline.OnValueChanged += (_, value) => bounce.Seek((int)value);
MarkupAnimation.EasingNames lists the names an Easing takes, for a tool offering them.
MarkupAnimation
A sealed class.
| Property | Type | Description |
|---|---|---|
Key |
string |
Read-only. The key the markup gives it, the include’s name before it for one of an included UI; null for none. |
Target |
BaseElement |
Read-only. The element whose property it animates. |
Property |
string |
Read-only. The name of the property it animates. |
StartOn |
string |
Read-only. What starts it, as the markup has it: Load, events (play.OnMouseEnter) or a list of them (Load, play.OnClick); null for none. |
StopOn |
string |
Read-only. The events that stop it, as the markup has them; null for none. |
DurationMs |
int |
Read-only. Its time line in milliseconds: its delay, and its steps’ pauses and times. One run, without its repeats and the way back of an auto reversing one. |
PositionMs |
int |
Read-only. Where its time line is now, in milliseconds from its start; 0 before it first starts or seeks, and after it stops. |
IsRunning |
bool |
Read-only. Whether it runs now: started, and neither completed nor stopped. |
Animation |
BaseAnimation |
Read-only. The BorrowedTorch.UI animation of its last start, made anew at each; null before its first start or seek. |
EasingNames |
IReadOnlyList<string> |
Static, read-only. The names an Easing takes, in any case: the class names of the shaping functions of BorrowedTorch.ShapingFunctions made by a constructor without parameters (Linear, CubicEaseOut). |
| Method | Description |
|---|---|
Start() |
Runs it from its beginning, again if it ran before, the markup’s other animations of the same property of the same element stopped first. |
Stop() |
Stops it where it is: the property keeps the value it set last. |
Seek(int positionMs) |
Shows a moment of it: the property given its value at the position, kept within 0 and DurationMs, the markup’s other animations of the same property of the same element stopped first. A running one goes on from there; one not running stays there until Start runs it from its beginning. |
The elements as written
A MarkupDocument keeps the markup’s elements as they are written, for a tool that shows them or finds where
one is written. Nodes is a tree of MarkupNodes, one per element written: the element it made, its type
name, the property a property element gives it to, the file, line and column it is written at, and the elements written
in it. An include is a node too, with its Source and no element, holding the elements of the UI it includes. Styles
and animations are no nodes: only elements are.
// the markup's tree, with where each element is written
void Print(MarkupNode node, int depth)
{
Console.WriteLine($"{new string(' ', depth * 2)}{node} at {node.Line}:{node.Column}");
foreach (var child in node.Children)
Print(child, depth + 1);
}
foreach (var node in document.Nodes)
Print(node, 0);
NodeOf finds an element’s node, for example the one clicked in a tool’s view. A part a control made for itself,
such as a slider’s thumb or a list’s row, has none: walk up its Parents to the element written.
MarkupNode WrittenAt(BaseElement element)
{
for (var current = element; current != null; current = current.Parent)
if (document.NodeOf(current) is { } node)
return node;
return null;
}
A node’s Position is the indexes of the XML elements from the root down to it, from 0, through the
includes: 1/0/2. The element at a position is the same element in the markup loaded again after an edit elsewhere in
it, so NodeAt keeps a tool’s selection across reloads:
var position = document.NodeOf(selected)?.Position;
document.Dispose();
document = UiMarkup.LoadDocumentFile(path, context);
selected = document.NodeAt(position)?.Element;
MarkupNode
A sealed class. Its ToString() is the type name and the element’s name, or Include and the source.
| Property | Type | Description |
|---|---|---|
Element |
BaseElement |
Read-only. The element made, null for an include. |
TypeName |
string |
Read-only. The type name as written (Button), or Include. |
Property |
string |
Read-only. The property a property element gives the element to (ToolTip for one in <Button.ToolTip>), null for an item, a content or an element under the root. |
Source |
string |
Read-only. An include’s Source as written, null for an element. |
File |
string |
Read-only. The full path of the file it is written in, the one loaded or an included one; null for a markup given as text. |
Line |
int |
Read-only. The line of its start tag in its file, from 1. |
Column |
int |
Read-only. The column of its start tag’s name, from 1. |
Position |
string |
Read-only. The indexes of the XML elements from the root down to it, from 0, through the includes (1/0/2). Property elements, <Ui.Styles> and <Ui.Animations> are counted. |
Parent |
MarkupNode |
Read-only. The node it is written in, null for one under the root. |
Children |
IReadOnlyList<MarkupNode> |
Read-only. The elements written in it, in the order they are written: its items or its content, the elements given to its properties, an include’s elements. |
A pause menu in markup
The quick start’s pause menu written as markup, with its handlers in a class of the game. The window’s title bar is a part the window makes itself, so its texts are set in code once the markup is loaded.
<Ui>
<Window Name="pause" DesiredWidth="260" DesiredHeight="210"
HorizontalAlignment="Center" VerticalAlignment="Center"
IsModal="true" OnKeyDown="CloseOnEscape">
<StackPanel Name="pauseButtons" Orientation="Vertical"
HorizontalAlignment="Center" VerticalAlignment="Center">
<Button Name="resume" Text="Resume" DesiredWidth="200" DesiredHeight="36" OnClick="Resume" />
<Button Name="settings" Text="Settings" DesiredWidth="200" DesiredHeight="36" Margin="0, 10" />
<Button Name="quit" Text="Quit to menu" DesiredWidth="200" DesiredHeight="36" Margin="0, 10"
OnClick="QuitToMenu" />
</StackPanel>
</Window>
</Ui>
public sealed class PauseMenu
{
private readonly Window _window;
public PauseMenu(BorrowedTorchUI ui)
{
_window = (Window)UiMarkup.LoadFile("UI/PauseMenu.btui", new MarkupContext { Handlers = this })[0];
var titleBar = (DefaultWindowTitleBar)_window.TitleBar;
titleBar.Title.Text = "Paused";
titleBar.CloseButton.Text = "x";
ui.AddElementToRoot(_window);
}
public void Show() => _window.Show();
private void Resume() => _window.Hide();
private void QuitToMenu() => Console.WriteLine("Back to the main menu");
// Escape closes the menu while anything in it has the keyboard
private void CloseOnEscape(BaseElement sender, KeyDownEventArgs e)
{
if (e.Key != Keys.Escape) return;
_window.Hide();
e.Handled = true;
}
}
Bound settings in markup
The bindings example of the styles page written as markup, bound to the same
SettingsViewModel. The label of the volume shows it through a PercentConverter, which a markup binding doesn’t
take: the markup gives the label a name, and code finds it and binds it.
<Ui>
<RichTextBox Name="name" Type="ReadWrite" DesiredWidth="220" DesiredHeight="30" TextMargin="8, 0"
VerticalTextAlignment="Center" BackgroundColor="40, 31, 23"
HorizontalAlignment="Left" VerticalAlignment="Top" Margin="16, 16"
Text="{Binding PlayerName, Mode=TwoWay}" />
<Label HorizontalAlignment="Left" VerticalAlignment="Top" Margin="252, 22" Text="{Binding Greeting}" />
<Slider DesiredWidth="220" DesiredHeight="18" Max="1" Margin="16, 66" Value="{Binding Volume, Mode=TwoWay}" />
<Label Name="volumeText" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="252, 66" />
<ListBox DesiredWidth="220" DesiredHeight="90" Margin="16, 100" ItemsSource="{Binding Levels}" />
</Ui>
var settings = new SettingsViewModel();
foreach (var element in UiMarkup.LoadFile("UI/Settings.btui", new MarkupContext { DataContext = settings }))
ui.AddElementToRoot(element);
// a binding with a converter is made in code
ui.GetElementByName<Label>("volumeText").TextDP.Bind(settings, nameof(settings.Volume), BindingMode.OneWay,
new PercentConverter());
Types and converters of your own
A type of your own is found by its name, as the UI’s are, once AddType adds it to the context. An
element needs a constructor taking its name, any other object (a style) a constructor without parameters. It takes the
place of a type of the UI with the same name.
A converter reads the values of one property type from text, in place of the markup’s own way for that type (a
converter of a type T reads T? too). AddConverter adds it. Both return the context, so the calls chain.
var context = new MarkupContext()
// an element of your own, with a constructor taking its name
.AddType<HealthBar>()
// its Cooldown is a TimeSpan, written in seconds
.AddConverter(text => TimeSpan.FromSeconds(double.Parse(text, CultureInfo.InvariantCulture)));
<Ui>
<HealthBar Name="health" DesiredWidth="200" DesiredHeight="16" Cooldown="1.5" />
</Ui>
MarkupContext
A sealed class.
| Property | Type | Description |
|---|---|---|
Handlers |
object |
The object whose methods the events name: OnClick="StartGame" subscribes its StartGame, public or not, taking the event’s parameters or none. |
MissingHandler |
Action<object, string, string> |
Called in place of a handler that Handlers doesn’t have, whenever its event is raised: with the element, the event’s name and the handler’s name. Set, a missing handler is no error. |
DataContext |
object |
The object {Binding Name} binds to, usually a Bindable view model. |
BaseDirectory |
string |
The directory a markup given as text finds its includes from. Without one, the current directory. |
ReadFile |
Func<string, string> |
Reads a markup file given its full path: the one loaded and the ones included. File.ReadAllText without one. |
StartsLoadAnimations |
bool |
Whether the animations started on Load start as the markup is loaded: true by default. false for a tool showing the UI as it is written, which starts them with StartLoadAnimations. |
| Method | Description |
|---|---|
MarkupContext() |
Creates a context without handlers, data context, styles, types or converters. |
AddType<T>() |
Makes a type of your own usable by its name, in place of a type of the UI with the same name. Returns the context. |
AddConverter<T>(Func<string, T> convert) |
Reads the values of type T from text with convert, in place of the markup’s own way. Returns the context. |
AddStyles(StyleDictionary styles) |
Makes the keyed styles of a style dictionary usable by their keys. A key in more than one dictionary names the style of the one added last. Returns the context. |
Errors
A markup that can’t be read throws a MarkupException, whose Message starts with the line and the
column, counted from 1 as text editors count them: Line 4, column 17: Button has no property Txt to set. Each
mistake is reported where it is written:
- XML that isn’t well formed, or a root other than
<Ui>(<Styles>for a style dictionary); - an unknown element or property, or a value that can’t be read;
- a child element where none is taken, or a second one where one content is taken;
- a binding without a data context, or to a property the data context doesn’t have;
- an event handler that is missing (without a
MissingHandler), or takes other parameters; - a style that isn’t there or doesn’t fit, two styles with one key, or two of one type without a key;
- a second
<Ui.Animations>, or an animation naming an element, a property or an event that isn’t there, a property that isn’t written as text, an attribute it doesn’t take, a value, time,RepeatorEasingthat can’t be read, or a key given twice; - an animation without steps missing its
ToorDuration, one with<Step>s giving either, or a step missing its own; - an include whose file can’t be read, that includes itself, or that holds a UI where styles are taken (or the other way round).
An error in an included file is reported at the include, followed by the file and its own place:
Line 4, column 9: Parts/Header.btui, line 2, column 17: Button has no property Txt to set. An animation’s value that
can’t be read is reported at its attribute, the reason starting with the attribute’s name:
Duration: 'soon' is no time in milliseconds (0 or more).
An exception thrown on the way, by a constructor, a setter or a converter, is the
InnerException. A load that fails keeps nothing of what it made: every element made so far is disposed.
MarkupException
A sealed class deriving from Exception.
| Property | Type | Description |
|---|---|---|
Line |
int |
Read-only. The line of the mistake, from 1; 0 when the place isn’t known. |
Column |
int |
Read-only. The column of the mistake, from 1; 0 when the place isn’t known. |
Reason |
string |
Read-only. What is wrong, without the place. |
Message |
string |
Read-only. Line {Line}, column {Column}: and the reason. |
InnerException |
Exception |
Read-only. The exception behind the mistake: the XML reader’s, or the one a constructor, a setter or a converter threw. null when there is none. |
| Method | Description |
|---|---|
MarkupException(string reason, int line, int column, Exception innerException = null) |
Creates the exception, its Message made of the place and the reason. |
Keeping markup in step with the UI
The markup finds the elements and their properties by name when it is read. A property renamed or removed in a later
BorrowedTorch.UI breaks a markup when it is loaded, not when the game is built: BorrowedTorch.UI 2.0.0 renamed
Border.Padding to ContentAreaMargin, so a markup still setting Padding throws at that
attribute. After updating BorrowedTorch.UI, load every markup file once (a test that loads each one is enough): a name
that changed throws a MarkupException pointing at it.