BorrowedTorch.UI.Markup
1.9.2
Prefix Reserved
dotnet add package BorrowedTorch.UI.Markup --version 1.9.2
NuGet\Install-Package BorrowedTorch.UI.Markup -Version 1.9.2
<PackageReference Include="BorrowedTorch.UI.Markup" Version="1.9.2" />
<PackageVersion Include="BorrowedTorch.UI.Markup" Version="1.9.2" />
<PackageReference Include="BorrowedTorch.UI.Markup" />
paket add BorrowedTorch.UI.Markup --version 1.9.2
#r "nuget: BorrowedTorch.UI.Markup, 1.9.2"
#:package BorrowedTorch.UI.Markup@1.9.2
#addin nuget:?package=BorrowedTorch.UI.Markup&version=1.9.2
#tool nuget:?package=BorrowedTorch.UI.Markup&version=1.9.2
BorrowedTorch.UI.Markup
Builds BorrowedTorch.UI element trees from XML markup, so a UI can be written as data: loaded by the game at run time, and edited live in a tool.
<Ui>
<StackPanel Name="menu" 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;
var context = new MarkupContext { Handlers = this, DataContext = settings };
foreach (var element in UiMarkup.LoadFile("UI/MainMenu.btui", context)) _ui.AddElementToRoot(element);
UiMarkup.Load reads a markup from a string and LoadFile from a file. Both give the elements under <Ui> in the order
they are written, not added anywhere yet. Load on the thread that updates the UI: the elements are made as code would make
them.
LoadDocument gives them in a MarkupDocument, which remembers every element the markup made. Disposing it disposes all
of them, the items and contents of its panels included: disposing a panel only detaches those. That is the way to take a
whole UI away, a screen left or a markup loaded again in its place:
_menu?.Dispose();
_menu = UiMarkup.LoadDocument(File.ReadAllText("UI/MainMenu.btui"), context);
foreach (var element in _menu.Elements) _ui.AddElementToRoot(element);
A document also has the markup's elements as written, for a tool showing them or finding where one is written:
Nodes is a tree of MarkupNodes, each with the element it made (Element), its TypeName, the Property a property
element gives it to, the File, Line and Column it is written at, and its Children. An include is a node holding
the elements of the UI it includes (its Source set, no element). NodeOf(element) finds an element's node (null for a
part a control made for itself: walk up its parents), and NodeAt(position) a node by its Position, the indexes of
the XML elements from the root down to it (1/0/2): the same element is at the same position in the markup loaded again
after an edit elsewhere in it, so a tool keeps a selection across reloads.
The markup
The root is <Ui>, and every element in it is one of the UI's elements by its type name: <Button>, <StackPanel>,
<Grid>. Name is the element's name, given when it is made (GetElementByName finds it). An element needs a
constructor taking its name, as all of the UI's own elements have; a few internal parts (ContextMenuItem, ListBoxItem)
have none and can't be written.
Attributes set the element's properties, the same ones code sets:
| Type | Written as |
|---|---|
| text | as it is |
| numbers | 120, 0.5 (a point, whatever the machine's culture) |
bool |
true, false |
| enums | the name of the value, in any case: Center, collapsed |
Color |
#RRGGBB, #RRGGBBAA, r, g, b or r, g, b, a (0 to 255), or a name: CornflowerBlue |
Margin |
5 (all sides), 10, 20 (left, top), 10, 20, 30, 10, 20, 30, 40, as in code |
Point, Vector2 |
x, y |
| converted from text | an image's Source: a content path, loaded through the UI's ContentManager as it is read |
A tool can read values as the markup does. UiMarkup.ReadValue(text, type, context) reads a text as an attribute
setting a property of the type is read, the context's converters first, and throws a FormatException with the reason a
markup would give for a text that can't be read; CanReadValue(type, context) tells whether a type is written as text at
all. An editor sets an element's properties from what is typed that way:
if (UiMarkup.CanReadValue(property.PropertyType))
property.SetValue(element, UiMarkup.ReadValue("10, 20", property.PropertyType)); // a Margin
UiMarkup.TryReadColor reads a text as a Color property's value is read, for a tool that shows the colours of a markup.
Child elements are the element's items (AddItem): the buttons of a panel, the rows of a list. An element with a
Content (a Border, a Button, a Window) holds one child element, its content. An element that takes neither (a
Label) refuses them. The text inside an element is its Text: <Label>Score</Label>.
Property elements give a property a value that is no text: an element of its own, a style, or a text too long for an attribute. They are named after the element and the property:
<Button Text="Save">
<Button.ToolTip>
<ToolTip Text="Save the game (Ctrl+S)" />
</Button.ToolTip>
<Button.TextStyle>
<LabelStyle FontSize="18" ForegroundColor="White" />
</Button.TextStyle>
</Button>
A style (or any other object of the UI that is no element) sets its properties by attributes too, and its own objects by property elements.
Grid columns and rows are listed in Columns and Rows: a size in units, auto (as large as the content) or a share
of what is left (*, 2*):
<Grid Columns="200, *" Rows="auto, *">
<Label Text="Title" GridColumnSpan="2" />
<ListBox GridRow="1" />
<Image GridColumn="1" GridRow="1" Source="Textures/Preview" />
</Grid>
Events name a method of the context's Handlers: OnClick="StartNewGame" subscribes its StartNewGame, public or not,
taking the event's parameters ((BaseElement sender, MouseClickEventArgs e)) 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:
var context = new MarkupContext
{
MissingHandler = (sender, eventName, handlerName) => Log($"{((BaseElement)sender).Name} {eventName}: {handlerName}")
};
MissingHandlerWithArguments is the same with the event's own arguments too - all it passes, the element first, then
what it tells - for code that handles events by name rather than by methods of its own (handlers registered by name):
var context = new MarkupContext
{
MissingHandlerWithArguments = (sender, eventName, handlerName, arguments) => handlers[handlerName](arguments)
};
A <Slider OnValueChanged="SetVolume" /> hands it [slider, 0.8f]; a check box's OnCheckedUnchecked, [box, true].
Bindings bind a property to one of the context's DataContext, a Bindable view model: Text="{Binding PlayerName}"
follows it, and Mode sets the direction ({Binding Volume, Mode=TwoWay}; OneWay without one). A text that starts with
a brace and is no binding starts with {}: Text="{}{not bound}".
Styles
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 one of the same type, before it in the dictionary or in a dictionary of the context:
<Styles>
<ButtonStyle DesiredHeight="32" NormalColor="SteelBlue" HoverColor="LightSteelBlue">
<ButtonStyle.TextStyle>
<LabelStyle ForegroundColor="White" />
</ButtonStyle.TextStyle>
</ButtonStyle>
<ButtonStyle Key="danger" NormalColor="DarkRed" HoverColor="Red" />
<ButtonStyle Key="bigDanger" BasedOn="danger" DesiredHeight="48" />
<LabelStyle Key="title" FontSize="24" />
</Styles>
var theme = UiMarkup.LoadStylesFile("UI/Theme.btui");
theme.ApplyGeneralStyles(); // Button.GeneralStyle: every button
var context = new MarkupContext().AddStyles(theme); // the keys, for the markups loaded with the context
A markup names a keyed style for an element with Style, which gives the element the style as its StyleOverride, and
for a style property with {Style key}:
<Button Text="Delete" Style="danger" />
<Button Text="Quit" TextStyle="{Style title}" />
The elements naming a style share it: a change made to it later (theme.Get<ButtonStyle>("danger").NormalColor = ...)
reaches all of them. ApplyGeneralStyles returns what puts the general styles there were before back when disposed, for
a theme that changes. A key in more than one dictionary of the context names the style of the one added last.
A UI can hold styles of its own in <Ui.Styles>, read before its elements wherever it is written. Their keys come
before the context's, and a style there without a key is given to the UI's elements of its type that name no style of
their own (the general styles of a dictionary are applied to every element of the game instead):
<Ui>
<Ui.Styles>
<ButtonStyle DesiredWidth="200" />
<LabelStyle Key="hint" FontSize="12" ForegroundColor="Gray" />
</Ui.Styles>
<StackPanel>
<Button Text="Play" />
<Label Text="Press F1 for help" Style="hint" />
</StackPanel>
</Ui>
Animations
A UI's <Ui.Animations> takes a property of one of its elements from a value to another over a time:
<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" />
</Ui>
| Attribute | What it is |
|---|---|
Target |
the element's Name (an included UI's: its include's name before it, left.play) |
Property |
any of its properties written as text: a dependency property, or one set through its setter |
From, To |
the values, written as the property's attribute is; without a From, from the value it has as it starts |
Duration |
in milliseconds; Delay before it |
Repeat |
Forever, or a number of runs (once without); AutoReverse="true" runs back after each run |
Easing |
a shaping function of BorrowedTorch.ShapingFunctions made without parameters (MarkupAnimation.EasingNames) |
StartOn |
Load, or an element's event (play.OnMouseEnter), or a list of them (Load, play.OnClick); without one, started by code |
StopOn |
an element's event, or a list of them: stops it where it is |
Key |
its name for code: document.FindAnimation("pulse").Start() |
An animation goes through several values one after another with <Step>s in place of its To and Duration, each
from where the one before ends (the first from the From), after a Delay of its own, with the animation's Easing
unless it has one:
<Animation Key="bounce" Target="logo" Property="Margin" From="0, 40" Repeat="Forever" Easing="CubicEaseOut">
<Step To="0, 10" Duration="300" />
<Step To="0, 40" Duration="300" Easing="CubicEaseIn" />
<Step To="0, 40" Duration="0" Delay="600" />
</Animation>
Starting an animation stops the markup's other animations of the same property of the same element, so that one
started as the mouse enters and one as it leaves take turns, the second from wherever the first left the value.
document.Animations lists them all (each with Start, Stop, IsRunning, DurationMs and PositionMs), and
disposing the document stops them. Seek(positionMs) shows a moment of one, for a tool scrubbing through it. The ones
started on load start as the markup is loaded, unless the context's StartsLoadAnimations is false: a tool showing the
UI as it is written starts them with document.StartLoadAnimations() when it is played.
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 is 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>
<StackPanel>
<Include Source="Parts/Header.btui" />
<Button Text="Play" />
<Include Source="Parts/VolumeSlider.btui" Name="music" />
<Include Source="Parts/VolumeSlider.btui" Name="effects" />
</StackPanel>
</Ui>
A Name on the include goes before the names of its elements: the slider of VolumeSlider.btui is music.slider and
effects.slider above, found apart with GetElementByName. An include where one element is taken (a Content, a
property element) gives the one element of its UI. An included UI names its own styles first (its <Ui.Styles>), then the
including one's, and takes the including one'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, of the same type) replaces the included one. A theme is made
of parts that way, and a screen can name its own theme without code:
<Ui>
<Ui.Styles>
<Include Source="Theme.btui" />
</Ui.Styles>
...
</Ui>
(The theme's general styles are then the screen's own, given to its elements only: 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. Every file is read through the context's ReadFile, File.ReadAllText
without one: a game whose files are elsewhere gives its own, and a tool can follow which files a markup read. A file that
can't be read, a file including itself, and an error in an included file are reported at the include, the latter with the
file, line and column it is at.
Types and converters of your own
var context = new MarkupContext()
.AddType<HealthBar>() // <HealthBar Name="health" />
.AddConverter(text => Enum.Parse<Rarity>(text, true)); // a type the markup can't read by itself
A type of your own is made by its name like the UI's: an element needs a constructor taking its name, any other object (a style) a constructor without parameters. A converter reads a property type from its text, in place of the markup's own way for that type.
Errors
A markup that can't be read throws a MarkupException: its Message starts with the line and the column, Line,
Column and Reason give them apart. An unknown element or property, a value that can't be read, a child element where
none is taken, a binding without a data context, a handler that is missing, a style that isn't there or doesn't fit:
each one is reported where it is written. A
read that fails keeps none of what it made: every element made so far is disposed.
Building and testing
dotnet test BorrowedTorch.UI.Markup.slnx
The tests in BorrowedTorch.UI.Markup.Tests read markup into elements of the BorrowedTorch.UI version the package
references, without a GraphicsDevice. The markup finds the elements' properties by reflection, so after a BorrowedTorch.UI
release, raise the reference and run them: a property renamed there breaks a markup at run time, not at compile time.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0-windows10.0.19041 is compatible. |
-
net10.0-windows10.0.19041
- BorrowedTorch.UI (>= 2.6.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.