Docs / UI

UI: styles, bindings and animation

Style classes, mouse cursors, default settings, dependency properties, view model bindings, items templates and animations.

Color legend plain property dependency property method event

Every element property listed on the element pages is a dependency property: Foo is backed by FooDP, a DependencyProperty<T> that a style, a binding or an animation sets (see dependency properties), and each element class has a static FooDPActions that holds what the class does when the value changes. This page covers what sets those properties: styles, bindings and animations, plus mouse cursors and the framework-wide defaults. None of the properties of the types on this page are dependency properties themselves. Screenshots use the theme shown in the next section.

Names are colored by what they are: a plain property, a method or an event.

The theme of these pages

Every screenshot on the UI pages is drawn with this theme. It changes a few framework-wide defaults and gives the element types general styles in dark browns and gold. The game calls Theme.Apply() once at start, before it creates the UI and its elements.

// the palette of the screenshots on these pages
static readonly Color Panel = new(26, 20, 15);
static readonly Color PanelLight = new(40, 31, 23);
static readonly Color Line = new(70, 56, 42);
static readonly Color Gold = new(233, 194, 122);
static readonly Color GoldDim = new(168, 131, 74);
static readonly Color Ink = new(20, 14, 10);
static readonly Color Text = new(217, 203, 180);
static readonly Color Flame = new(242, 140, 40);

public static void Apply()
{
    // framework-wide defaults: set them before the UI and its elements are created
    BaseElement.ModalWindowActiveShadeTint = new Color(0, 0, 0, 150);
    DefaultSettings.DefaultFontSize = 16;
    DefaultSettings.DefaultTextColor = Text;
    DefaultSettings.DefaultTextCursorColor = Gold;
    DefaultSettings.DefaultTextSelectionColor = new Color(168, 131, 74, 120);
    DefaultSettings.DefaultWindowBackgroundColor = Panel;
    DefaultSettings.DefaultWindowTitleBarColor = PanelLight;
    DefaultSettings.DefaultWindowBorderColor = GoldDim;
    DefaultSettings.DefaultWindowBorderThickness = 1;
    DefaultSettings.DefaultContextMenuBackgroundColor = PanelLight;
    DefaultSettings.DefaultContextMenuBorderColor = GoldDim;
    DefaultSettings.DefaultContextMenuHighlightColor = new Color(80, 60, 38);
    DefaultSettings.DefaultContextMenuIconColor = Gold;

    var scrollBars = new SliderStyle
    {
        ButtonsSolidColor = Line,
        LineDecreaseSolidColor = PanelLight,
        LineIncreaseSolidColor = PanelLight,
        ThumbSolidColor = new Color(110, 88, 62)
    };

    // every element of a type takes its general style
    Button.GeneralStyle = new ButtonStyle
    {
        NormalColor = GoldDim,
        HoverColor = Gold,
        PressedColor = new Color(128, 98, 54),
        ToggledColor = Flame,
        TextStyle = new LabelStyle { ForegroundColor = Ink }
    };

    CheckBox.GeneralStyle = new CheckBoxStyle
    {
        HorizontalAlignment = HorizontalAlignment.Left,
        VerticalAlignment = VerticalAlignment.Top,
        CheckedSolidColor = Gold,
        UncheckedSolidColor = Line
    };

    Slider.GeneralStyle = new SliderStyle
    {
        ButtonsSolidColor = Line,
        LineDecreaseSolidColor = Gold,
        LineIncreaseSolidColor = PanelLight,
        ThumbSolidColor = new Color(240, 227, 204),
        TickPassedColor = Gold,
        TickRemainingColor = Line
    };

    ProgressBar.GeneralStyle = new ProgressBarStyle
    {
        BackgroundColor = PanelLight,
        ForegroundColor = Gold
    };

    ScrollableContainer.GeneralStyle = new ScrollableContainerStyle
    {
        ScrollBarsThickness = 10,
        ScrollBarsStyle = scrollBars
    };

    ListBox.GeneralStyle = new ListBoxStyle
    {
        BackgroundColor = Panel,
        UseDualColors = true,
        NormalItemColor = Panel,
        AlternativeItemColor = new Color(31, 24, 18),
        HoverItemColor = new Color(58, 44, 30),
        PressedItemColor = new Color(80, 60, 38),
        SelectedItemColor = new Color(110, 82, 48),
        ScrollableContainerStyle = new ScrollableContainerStyle
        {
            ScrollBarsThickness = 10,
            ScrollBarsStyle = scrollBars
        }
    };

    ComboBox.GeneralStyle = new ComboBoxStyle
    {
        BackgroundColor = PanelLight,
        ToggleButtonStyle = new ButtonStyle
        {
            NormalColor = GoldDim,
            HoverColor = Gold,
            PressedColor = new Color(128, 98, 54),
            ToggledColor = Gold,
            TextStyle = new LabelStyle { ForegroundColor = Ink }
        }
    };

    TreeView.GeneralStyle = new TreeViewStyle
    {
        // the size and place of the expand icon: the tree view on these
        // pages draws its arrow pictures (FoldedIcon and ExpandedIcon,
        // from its TexturesPath) in this box
        ExpandIconStyle = new ImageStyle
        {
            DesiredWidth = 10,
            DesiredHeight = 10,
            Margin = (4, 0, 6, 0),
            VerticalAlignment = VerticalAlignment.Center,
            HitTest = false
        },
        ListBoxStyle = new ListBoxStyle
        {
            BackgroundColor = Panel,
            NormalItemColor = Panel,
            HoverItemColor = new Color(58, 44, 30),
            SelectedItemColor = new Color(110, 82, 48)
        }
    };

    ToolTip.GeneralStyle = new ToolTipStyle
    {
        BackgroundColor = new Color(52, 40, 29),
        TextStyle = new LabelStyle { ForegroundColor = Text, TextMargin = (8, 5) }
    };
}

Set DefaultSettings first: the framework defaults of a style type read DefaultSettings once, the first time that style type is used (see default settings).

Styles

Every element type X that has a style has an XStyle class with the same properties as X’s dependency properties. A style is applied at one of two levels: X.GeneralStyle for every element of the type, and element.StyleOverride for one element, over its general style. A value set in code wins over both.

Three buttons in a row: a gold Keep button, a dark red Delete save button with light text, and a green Own color button
The general button style, a style override, and a color set in code.
// a style for one element, over the general style of its type
var danger = new ButtonStyle
{
    NormalColor = new Color(150, 52, 30),
    HoverColor = new Color(190, 70, 40),
    PressedColor = new Color(110, 38, 22),
    TextStyle = new LabelStyle { ForegroundColor = new Color(255, 236, 214) }
};

var row = new StackPanel { Orientation = Orientation.Horizontal, Margin = (16, 18) };

row.AddItem(new Button { Text = "Keep", DesiredWidth = 140, DesiredHeight = 36 });
row.AddItem(new Button
{
    Text = "Delete save",
    DesiredWidth = 140,
    DesiredHeight = 36,
    Margin = (16, 0),
    StyleOverride = danger
});

// a value set in code wins over every style
row.AddItem(new Button
{
    Text = "Own color",
    DesiredWidth = 140,
    DesiredHeight = 36,
    Margin = (16, 0),
    NormalColor = new Color(120, 140, 90)
});

ui.AddElementToRoot(row);

A style applies only the properties assigned to it, also when a property is assigned its type’s default value. A new style has none assigned, so new ButtonStyle { NormalColor = Color.Red } changes the color and leaves everything else to the level below. The “Delete save” button above takes its colors from danger and its size from code; anything danger doesn’t assign comes from Button.GeneralStyle.

  • General style. X.GeneralStyle (static) lies over the framework defaults of the type: a property it leaves unassigned takes the framework default (listed in the style classes table), or the property’s own default when the type has none. It starts as a copy of the framework defaults, so reading Button.GeneralStyle gives the defaults and changing one of its properties in place keeps the others. Assigning a new style replaces it as a whole; setting it to null leaves only the framework defaults.
  • Style override. element.StyleOverride applies to one element. Its unassigned properties fall through to the general style. Setting it back to null removes its values from the element.
  • Live changes. Changing a property of a style in use, or replacing a general style, updates every element that uses it. Changes are delivered by walking the element tree; an element that is not in the tree at that moment (created but not added yet, or removed) catches up when it is attached.
  • Part styles. Properties such as ButtonStyle.TextStyle or ListBoxStyle.ScrollableContainerStyle hold the style of a part inside the control. The part takes it as its own StyleOverride, so it lies over the part type’s general style: TextStyle = new LabelStyle { ForegroundColor = ... } changes the text color and keeps the rest of Label.GeneralStyle.
  • No style class. Grid, Separator, TabControl and the parts that only exist inside an element (ListBoxItem, TreeViewItem, ContextMenuItem, GridCell, ContentContainer, DefaultWindowTitleBar) have no style. They are set in code; their double click interval, repeat timings and resize area come from DefaultSettings like every element’s.

StyleOverride, GeneralStyle, MouseCursorsSetOverride and GeneralMouseCursorsSet are members of every styled element, described on the base element page.

Value priority

Each dependency property keeps up to three values, one per source, and uses the one with the highest priority: ManualAssign > StyleOverride > GeneralStyle. With none of them set it reads its default. Bindings and animations write ManualAssign values like code does. To give a property set in code back to the styles, clear its manual value:

button.NormalColorDP.ClearValue(ValueSources.ManualAssign); // the style's color again

FooDP.ValueSource tells where the value in effect comes from. A tool that shows an element’s properties asks the element instead, by the property’s name: ValueSourceOf doesn’t create the dependency property, so a property the element hasn’t used yet reads None, and it gives null for a name that is no dependency property of the element (see inspecting elements).

var button = new Button();

button.ValueSourceOf(nameof(Button.NormalColor)); // GeneralStyle: Button.GeneralStyle sets it
button.ValueSourceOf(nameof(Button.Text));        // None: no source has a value

button.StyleOverride = new ButtonStyle { NormalColor = Color.DarkRed };
button.ValueSourceOf(nameof(Button.NormalColor)); // StyleOverride

button.ValueSourceOf("ActualWidth");              // null: no dependency property

ValueSources

Value Meaning
ManualAssign A value set in code (element.Foo = ... or FooDP.SetValue), by a binding or by an animation. Highest priority.
StyleOverride A value from the element’s StyleOverride.
GeneralStyle A value from the general style of the type, or from the framework defaults under it. Lowest priority.
None No source has a value: the property reads its default. Returned by ValueSource and ValueSourceOf; setting or clearing with it does nothing.

BaseStyle

The abstract base of every style class. It has one property for each dependency property of BaseElement (Margin, DesiredWidth, DesiredHeight, MinWidth, MinHeight, MaxWidth, MaxHeight, HorizontalAlignment, VerticalAlignment, Visibility, Disabled, BackgroundColor, ForegroundColor, TexturesPath, Transparency, InheritState, HitTest, GridRow, GridColumn, GridRowSpan, GridColumnSpan, ZIndex, RepeatClicks, TimeBeforeRepeatStartsMs, TimeBetweenRepeatsMs, DoubleClickIntervalMs, CropOutsideOfParentBorder, IsResizable, ResizeWithElementContour, ResizeContourColor, ResizeAreaHalfWidth, DragType, CustomEffect), with the same names and types, so every style class has them too. Setting a property assigns it, even to the value it already has. The framework defaults of every style type include HitTest = true and CropOutsideOfParentBorder = true.

Method Description
IsSet(string propertyName) Whether the property is assigned to this style, so the style applies it. Pass the name with nameof; an unknown name gives false.
Unset(string propertyName) Takes the property back out of the style: the style stops applying it, it reads its type’s default again, and the elements using the style update.
Clone() Returns a copy (as object) with the same properties assigned. Part styles in it are copied too.

Style classes

Each style class has a public parameterless constructor that creates a style with nothing assigned, and the properties of its element’s dependency properties (see the element’s section) except the ones in the third column. None has properties beyond its element’s. The last column lists the framework defaults the class assigns on top of the BaseStyle ones; they are what the general style starts with.

Style class Element Part styles, and element properties left out Framework defaults
BorderStyle Border Leaves out Content. Thickness DefaultBorderThickness (1) and ForegroundColor DefaultBorderColor: a frame that shows, around a clear content area.
ButtonStyle Button Part styles TextStyle (LabelStyle) and BackgroundStyle (ImageStyle). Leaves out Content. NormalColor, HoverColor, PressedColor and ToggledColor from DefaultButtonNormalColor, DefaultButtonHoverColor, DefaultButtonPressedColor and DefaultButtonToggledColor.
CheckBoxStyle CheckBox Part styles TextStyle (LabelStyle) and ImageStyle (ImageStyle). Leaves out Content. CheckedSolidColor DefaultCheckBoxCheckedColor, UncheckedSolidColor DefaultCheckBoxUncheckedColor.
ColorPickerStyle ColorPicker Leaves out Brightness and SelectedColor, so it has only the BaseStyle properties. ForegroundColor white.
ComboBoxStyle ComboBox Part styles SelectionStyle (ImageStyle), ToggleButtonStyle (ButtonStyle) and ListBoxStyle (ListBoxStyle). Aligned left and top, InheritState.FromChildren, BackgroundColor DefaultComboBoxBackgroundColor, and a ToggleButtonStyle DefaultComboBoxToggleButtonWidth (24) wide with the text v. The toggle button’s colors and the drop-down list’s are the defaults of Button and ListBox.
ContextMenuStyle ContextMenu Part styles BorderStyle, ListBoxStyle, CheckIconStyle and ExpandIconStyle (ImageStyle). Leaves out ItemsSource. Aligned left and top, HitTest off, Placement BottomRight. A border 1 unit thick in the context menu colors of DefaultSettings; a transparent list without dual colors whose hover and selected rows use DefaultContextMenuHighlightColor; an 8 by 8 check icon and a 6 by 8 expand icon in DefaultContextMenuIconColor.
ImageStyle Image None. ForegroundColor white.
LabelStyle Label None. Text empty, FontSize DefaultFontSize, ForegroundColor DefaultTextColor, HitTest off, InheritState.FromParent.
ListBoxStyle ListBox Part style ScrollableContainerStyle. Leaves out SelectedItem, SelectedIndex and ItemsSource. InheritState.FromChildren, BackgroundColor DefaultListBoxBackgroundColor, AlternativeItemColor, HoverItemColor, PressedItemColor and SelectedItemColor from their DefaultListBox settings, ItemHeight DefaultListBoxItemHeight (24). NormalItemColor stays transparent.
ProgressBarStyle ProgressBar None. BackgroundColor DefaultProgressBarBackgroundColor (the track), ForegroundColor DefaultProgressBarColor (the bar), Max 1.
RichTextBoxStyle RichTextBox Part styles ScrollBarsStyle (SliderStyle) and BackgroundStyle (ImageStyle). Text empty, InheritState.FromChildren, and FontSize, ForegroundColor, TextCursorThickness, TextCursorColor, TextSelectionColor and ScrollBarsThickness from DefaultSettings.
RootElementStyle RootElement Only the BaseStyle properties. None beyond the base ones.
ScrollableContainerStyle ScrollableContainer Part style ScrollBarsStyle (SliderStyle), used by both scroll bars (the vertical one with its two line colors swapped). InheritState.FromChildren, ScrollBars Both, ScrollBarsThickness DefaultScrollBarsThickness (12), and a ScrollBarsStyle with DefaultScrollBarsTrackColor on both sides of a DefaultScrollBarsThumbColor thumb, and DefaultScrollBarsButtonsColor buttons.
SliderStyle Slider None. InheritState.FromChildren, ThumbScale (1, 1), Max 1, and the solid colors, tick colors, TickSize, TickOffset and ThumbMinSize from their DefaultSlider settings.
StackPanelStyle StackPanel None. Aligned left and top, HitTest off, InheritState.FromChildren.
StencilStyle Stencil Leaves out SourceTexture and StencilTexture. None beyond the base ones.
ToolTipStyle ToolTip Part style TextStyle (LabelStyle). Leaves out Content. Aligned left and top, HitTest off, TimeBeforeShowMs DefaultTimeBeforeShowToolTipMs, BackgroundColor DefaultToolTipBackgroundColor, Placement BottomRight, MarginFromMouseCursor DefaultToolTipMarginFromMouseCursor (14, 14).
TreeViewStyle TreeView Part styles ListBoxStyle and ExpandIconStyle (ImageStyle). Leaves out SelectedItem and ItemsSource. An ExpandIconStyle of an 8 by 8 block, centered, FoldedIconColor (150, 150, 160), ExpandedIconColor (90, 90, 100), SubItemsShift DefaultTreeViewSubItemsShift (16, 0). Its list takes the defaults of ListBox.
ViewPortStyle ViewPort None. HitTest off, MinDepth and MaxDepth from DefaultSettings.
WindowStyle Window Part style BorderStyle. Leaves out TitleBar and Content. A border DefaultWindowBorderThickness thick, filled with DefaultWindowBackgroundColor, in DefaultWindowBorderColor.

DefaultWindowTitleBarStyle is an empty class that does not derive from BaseStyle; nothing uses it, and DefaultWindowTitleBar has no style.

GenericStyle<T>

The static holder of the general style of one style type, where T is the style class. Button.GeneralStyle reads and writes GenericStyle<ButtonStyle>.GeneralStyle. It also keeps the framework defaults of the type, built the first time the type is used from the class’s defaults (internal, not reachable from your code).

Property Type Description
GeneralStyle T Static. The style every element of the type takes, over the framework defaults. Starts as a copy of the defaults; null leaves only the defaults.
Event Handler Raised when
OnGeneralStyleChanged (T prevStyle) Static. GeneralStyle is replaced by another style; the handler gets the previous one. Not raised when a property of the style changes.

Mouse cursors

Mouse cursors are chosen in the same layers as styles. An element with a style class shows, in this order of priority:

  1. its own set, element.MouseCursorsSetOverride;
  2. the set given by hand (MouseCursorsSetOverride) to the control it is a part of;
  3. the general set of its type, X.GeneralMouseCursorsSet (null at start);
  4. BaseElement.DefaultMouseCursorsSet, which BorrowedTorchUI.SetDefaultMouseCursorsSet also sets.

So a set given to a control reaches the controls inside it (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 on the control, those parts keep their own type’s GeneralMouseCursorsSet (a list’s scroll bars use Slider.GeneralMouseCursorsSet). A part without a style class shows its owner’s cursors. Your own elements placed in a control keep their own cursors. Changing a property of a set in use, or replacing a general or default set, updates the elements.

Button.GeneralMouseCursorsSet = new MouseCursorsSet
{
    // LoadPng: your own loader of PNG files as Texture2D
    HoverCursor = MouseCursor.FromTexture2D(
        LoadPng("UITextures/MouseCursors/ArrowHover.png"), 0, 0),
    PressedCursor = MouseCursor.FromTexture2D(
        LoadPng("UITextures/MouseCursors/ArrowPressed.png"), 0, 0)
};

A cursor property left null sets no cursor, so the one shown before stays. The default set shows the arrow over the elements, the sizing arrows on the edges and corners 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. It has no other pressed cursors, so the hover cursor stays while a button is held.

A disabled element still takes the mouse, without being hovered, and shows only the plain HoverCursor of its set (the arrow in the default set): no drag, text or link cursor, and not the cursor of the element the mouse came from.

The Example columns below show the cursors of the UITextures/MouseCursors folder that comes with BorrowedTorch.UI (the set the snippet above loads from), the hover cursor first and the pressed one second where a set has both. They are one possible look: any picture can be a cursor (MouseCursor.FromTexture2D).

MouseCursorsSet

The cursors an element shows. It is disposable: disposing it disposes its DragAndDropCursors, ResizeCursors and RichTextCursors, and a disposed set ignores new values.

Property Type Description Example
HoverCursor MouseCursor The cursor while the mouse is over the element. A disabled element shows only this one. arrow cursor
PressedCursor MouseCursor The cursor while the left button is held on the element. pressed arrow cursor
DragAndDropCursors DragAndDropCursors The cursors of a draggable element and of drop targets.  
ResizeCursors ResizeCursors The cursors on the edges and corners of a resizable element.  
RichTextCursors RichTextCursors The cursors over the text of a rich text box.  
Method Description
MouseCursorsSet() Creates an empty set.
Clone() Returns a copy (as object), with copies of the three nested sets; the MouseCursor objects are shared. Returns null for a disposed set.

DragAndDropCursors

The cursors of drag and drop. Disposable like MouseCursorsSet.

Property Type Description Example
DragHoverCursor MouseCursor Shown instead of HoverCursor over an element that can be dragged. open hand cursor
DragPressedCursor MouseCursor Shown instead of PressedCursor while the left button is held on an element that can be dragged. grabbing hand cursor
DropAllowedCursor MouseCursor Shown over a drop target that accepts what is dragged. drop allowed cursor
DropDeniedCursor MouseCursor Shown over a drop target that refuses what is dragged. drop denied cursor
Method Description
DragAndDropCursors() Creates an empty set.
Clone() Returns a copy (as object), or null when disposed.

ResizeCursors

The cursors of the eight grips around a resizable element. Each grip is a MouseCursorsSet, so it can have a hover and a pressed cursor. A sealed, disposable class.

Property Type Description Example
LeftTop MouseCursorsSet The top left corner. top left resize cursor, hover top left resize cursor, pressed
RightTop MouseCursorsSet The top right corner. top right resize cursor, hover top right resize cursor, pressed
LeftBottom MouseCursorsSet The bottom left corner. bottom left resize cursor, hover bottom left resize cursor, pressed
RightBottom MouseCursorsSet The bottom right corner. bottom right resize cursor, hover bottom right resize cursor, pressed
Left MouseCursorsSet The left edge. left resize cursor, hover left resize cursor, pressed
Right MouseCursorsSet The right edge. right resize cursor, hover right resize cursor, pressed
Top MouseCursorsSet The top edge. top resize cursor, hover top resize cursor, pressed
Bottom MouseCursorsSet The bottom edge. bottom resize cursor, hover bottom resize cursor, pressed
Method Description
ResizeCursors() Creates an empty set.
Clone() Returns a copy (as object) that shares the eight sets, or null when disposed.

RichTextCursors

The cursors over the text of a RichTextBox. They replace the hover and pressed cursors of the box’s set. Disposable like MouseCursorsSet.

Property Type Description Example
WriteCursor MouseCursorsSet Its hover and pressed cursors are shown over the text of an editable (ReadWrite) box. text cursor, hover text cursor, pressed
LinkCursor MouseCursorsSet Its hover and pressed cursors are shown over a link in a box that is not editable. link cursor, hover link cursor, pressed
Method Description
RichTextCursors() Creates an empty set.
Clone() Returns a copy (as object) that shares the two sets, or null when disposed.

GenericMouseCursorsData<T>

The static holder of the general mouse cursors set of one element type, keyed by its style class T. Button.GeneralMouseCursorsSet reads and writes GenericMouseCursorsData<ButtonStyle>.GeneralMouseCursorsSet.

Property Type Description
GeneralMouseCursorsSet MouseCursorsSet Static. The set of every element of the type that has none of its own. null at start, which means the default set.
Event Handler Raised when
OnGeneralMouseCursorsSetChanged (MouseCursorsSet prevMouseCursorsSet) Static. GeneralMouseCursorsSet is replaced; the handler gets the previous set. Not raised when a property of the set changes.

Showing the cursors

The UI doesn’t show a cursor itself: it hands the cursor an element asks for to BorrowedTorchUI.MouseCursorHandler. In a game that is MonoGame’s Mouse.SetCursor, which shows it through the game window, and there is nothing to set. A UI hosted outside a game window, such as an editor’s viewport, has no window for Mouse.SetCursor, which throws there: give the handler your host’s own way of showing a MouseCursor, or null to show no cursors. The hover and the presses work the same either way.

// ShowHostCursor stands for the host's own code. With WindowsDX a cursor's Handle
// is a Windows cursor handle, the kind Win32's SetCursor takes.
_ui.MouseCursorHandler = cursor => ShowHostCursor(cursor.Handle);

The handler never gets null: a cursor left null in a set isn’t handed on. Set it after creating the UI, since disposing a UI puts MonoGame’s way back for the next one.

Texture sets

An element whose TexturesPath names a content folder draws pictures from that folder instead of its solid colors. It loads each picture by a fixed name: the asset name the content pipeline gives it, its file name without the extension. So a button with TexturesPath = "UITextures/Button/" loads UITextures/Button/Normal (compiled from Normal.png) and the others below. A name the element loads has to be in the folder: when it is missing, the content manager throws a ContentLoadException. The pictures are drawn in their own colors.

The examples are one possible look. Any pictures with these names work, at any size: each is stretched or tiled over its part as the tables say.

Border textures

Border, and the frame of a Window, a ContextMenu and a RichTextBox (their BorderStyle). All eight are loaded together, each one stretched over its part.

Texture Part Example
LeftTop The top left corner. The LeftTop texture of the example border
RightTop The top right corner. The RightTop texture of the example border
LeftBottom The bottom left corner. The LeftBottom texture of the example border
RightBottom The bottom right corner. The RightBottom texture of the example border
Left The left side, between the left corners. The Left texture of the example border
Right The right side, between the right corners. The Right texture of the example border
Top The top side, between the top corners. The Top texture of the example border
Bottom The bottom side, between the bottom corners. The Bottom texture of the example border

Button textures

Button, and the buttons inside other elements: the toggle button of a ComboBox (its ToggleButtonStyle) and the CloseButton of a window’s DefaultWindowTitleBar. Each texture is stretched over the button (its BackgroundStyle can give another Fill). A texture is loaded the first time the button shows its state, so a button that is never a Toggle needs no Toggled.

Texture Shown when Example
Normal The button is at rest. The Normal texture of the example button
Hover The mouse is over the button. The Hover texture of the example button
Pressed The left button is held down on it. The Pressed texture of the example button
Toggled A Toggle button is on (ToggledOn), at rest or under the mouse. Pressed still shows while it is held down. The Toggled texture of the example button

CheckBox textures

Stretched over the box’s square. A radio button (Type RadioButton) takes the same names, from a folder of its own for another look. Each one is loaded the first time the box shows it.

Texture Shown when Example
Checked Checked is true. The Checked texture of the example check box
Unchecked Checked is false. The Unchecked texture of the example check box

ProgressBar textures

Both are loaded together and tiled.

Texture Part Example
Background The track, tiled over the whole bar. The Background texture of the example progress bar
Bar The filled part, tiled over it. The Bar texture of the example progress bar

Slider textures

Slider, and the scroll bars of a ScrollableContainer and a RichTextBox (their ScrollBarsStyle) and of a ListBox (its ScrollableContainerStyle). A slider loads the seven textures of its Orientation and Type: the caps or the buttons at its ends, the two halves of the track and the three pieces of the thumb. A vertical slider starts at the bottom. ScrollBarNoButtons loads the button textures too, though it doesn’t show them. The track halves and the thumb’s middle are tiled along the slider, the rest is stretched.

Texture Part Orientation Example
LeftEnd Start cap (Slider, SliderWithCaps) Horizontal The LeftEnd texture of the example slider
BottomEnd Start cap (Slider, SliderWithCaps) Vertical The BottomEnd texture of the example slider
RightEnd End cap (Slider, SliderWithCaps) Horizontal The RightEnd texture of the example slider
TopEnd End cap (Slider, SliderWithCaps) Vertical The TopEnd texture of the example slider
LeftButton Start button (ScrollBar, ScrollBarNoButtons) Horizontal The LeftButton texture of the example slider
DownButton Start button (ScrollBar, ScrollBarNoButtons) Vertical The DownButton texture of the example slider
RightButton End button (ScrollBar, ScrollBarNoButtons) Horizontal The RightButton texture of the example slider
UpButton End button (ScrollBar, ScrollBarNoButtons) Vertical The UpButton texture of the example slider
HorizontalDecrease Track before the thumb (tiled) Horizontal The HorizontalDecrease texture of the example slider
VerticalDecrease Track before the thumb (tiled) Vertical The VerticalDecrease texture of the example slider
HorizontalIncrease Track after the thumb (tiled) Horizontal The HorizontalIncrease texture of the example slider
VerticalIncrease Track after the thumb (tiled) Vertical The VerticalIncrease texture of the example slider
ThumbLeft Thumb’s start Horizontal The ThumbLeft texture of the example slider
ThumbBottom Thumb’s start Vertical The ThumbBottom texture of the example slider
ThumbHorizontal Thumb’s middle (tiled) Horizontal The ThumbHorizontal texture of the example slider
ThumbVertical Thumb’s middle (tiled) Vertical The ThumbVertical texture of the example slider
ThumbRight Thumb’s end Horizontal The ThumbRight texture of the example slider
ThumbTop Thumb’s end Vertical The ThumbTop texture of the example slider

TreeView textures

The expand icon before an item with leaves, at the size of ExpandIconStyle. Both are loaded when an item shows its icon. The example is the arrow pair these pages use.

Texture Shown Example
FoldedIcon The item’s branch is collapsed. The FoldedIcon texture of the example tree view
ExpandedIcon The item’s branch is expanded. The ExpandedIcon texture of the example tree view

Default settings

Every element shows and works without any setting, in a light theme: black text, wheat windows, white lists, combo boxes and context menus, and gray controls with a blue accent for what is on or done (a checked box, the passed part of a slider or a progress bar, a toggled button). Buttons light up under the mouse and when pressed, list rows when hovered, pressed and selected; borders have a 1 unit 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 and to the right of the cursor; a tree view indents its children; a separator is a gray line. What you set in code, in a style override or in a general style replaces any of it, as the theme of these pages does.

DefaultSettings (namespace BorrowedTorch.UI.Settings) is a static class of public fields that hold framework-wide defaults. Set them at start, before you create elements. Most are read when the framework defaults of a style type are built, which happens once, the first time that style type is used (normally when the first element of the type is created, or when you touch X.GeneralStyle); changing them later doesn’t reach that type. The ones marked “on use” are read each time they are needed. They hold the colors and sizes of the light theme, so changing them re-themes every element at once.

Field Type Default Description
DefaultFontSize int 14 The FontSize default of LabelStyle and RichTextBoxStyle.
DefaultTextColor Color Color.Black The ForegroundColor default of LabelStyle and RichTextBoxStyle.
DefaultTextCursorThickness int 1 The TextCursorThickness default of RichTextBoxStyle, in units.
DefaultTextCursorColor Color Color.Black The TextCursorColor default of RichTextBoxStyle.
DefaultTextSelectionColor Color Color.LightBlue The TextSelectionColor default of RichTextBoxStyle.
DefaultTextCursorBlinkTimeMs int 500 How long the text cursor stays on and off, in milliseconds. Read when a text cursor starts blinking.
DefaultResizeAreaHalfWidth int 3 On use. The ResizeAreaHalfWidth default of every element: half the width of the grips of a resizable element, in units.
DefaultResizeContourHalfWidth int 1 On use. Half the width of the contour drawn while an element is resized, in units.
DefaultResizeContourColor Color new(50, 50, 50, 190) On use. The ResizeContourColor default of every element.
DefaultWindowTitleThickness int 30 The height of a window’s default title bar (its close button is 4 units smaller). Read when a window is created, and for the close button when the title bar is measured.
DefaultWindowBorderThickness int 2 The border thickness of WindowStyle’s default border.
DefaultWindowBackgroundColor Color Color.Wheat The background color of WindowStyle’s default border.
DefaultWindowTitleBarColor Color Color.LightBlue The background color of a window’s default title bar, read when the title bar is created.
DefaultWindowBorderColor Color new(80, 80, 80, 255) The border color of WindowStyle’s default border.
DefaultBorderThickness int 1 The Thickness default of BorderStyle, in units.
DefaultBorderColor Color new(80, 80, 80, 255) The frame color (ForegroundColor) default of BorderStyle.
DefaultButtonNormalColor Color new(225, 225, 230, 255) The NormalColor default of ButtonStyle.
DefaultButtonHoverColor Color new(200, 220, 240, 255) The HoverColor default of ButtonStyle.
DefaultButtonPressedColor Color new(160, 190, 225, 255) The PressedColor default of ButtonStyle.
DefaultButtonToggledColor Color new(86, 156, 214, 255) The ToggledColor default of ButtonStyle.
DefaultCheckBoxCheckedColor Color new(86, 156, 214, 255) The CheckedSolidColor default of CheckBoxStyle.
DefaultCheckBoxUncheckedColor Color new(150, 150, 160, 255) The UncheckedSolidColor default of CheckBoxStyle.
DefaultSliderLineDecreaseColor Color new(86, 156, 214, 255) The LineDecreaseSolidColor default of SliderStyle.
DefaultSliderLineIncreaseColor Color new(150, 150, 160, 255) The LineIncreaseSolidColor default of SliderStyle.
DefaultSliderThumbColor Color new(80, 80, 80, 255) The ThumbSolidColor default of SliderStyle.
DefaultSliderButtonsColor Color new(150, 150, 160, 255) The ButtonsSolidColor default of SliderStyle.
DefaultSliderTickPassedColor Color new(86, 156, 214, 255) The TickPassedColor default of SliderStyle.
DefaultSliderTickRemainingColor Color new(150, 150, 160, 255) The TickRemainingColor default of SliderStyle.
DefaultSliderTickSize Point new(2, 2) The TickSize default of SliderStyle, in units.
DefaultSliderTickOffset int 2 The TickOffset default of SliderStyle, in units.
DefaultSliderThumbMinSize float 10 The ThumbMinSize default of SliderStyle, in units.
DefaultScrollBarsThickness int 12 The ScrollBarsThickness default of ScrollableContainerStyle and RichTextBoxStyle, in units.
DefaultScrollBarsTrackColor Color new(230, 230, 235, 255) The color of both track halves in the default ScrollBarsStyle of ScrollableContainerStyle.
DefaultScrollBarsThumbColor Color new(150, 150, 160, 255) The thumb color in the default ScrollBarsStyle of ScrollableContainerStyle.
DefaultScrollBarsButtonsColor Color new(190, 190, 200, 255) The color of the end buttons in the default ScrollBarsStyle of ScrollableContainerStyle.
DefaultProgressBarBackgroundColor Color new(225, 225, 230, 255) The track color (BackgroundColor) default of ProgressBarStyle.
DefaultProgressBarColor Color new(86, 156, 214, 255) The bar color (ForegroundColor) default of ProgressBarStyle.
DefaultListBoxBackgroundColor Color Color.White The BackgroundColor default of ListBoxStyle.
DefaultListBoxAlternativeItemColor Color new(240, 240, 245, 255) The AlternativeItemColor default of ListBoxStyle, shown with UseDualColors.
DefaultListBoxHoverItemColor Color new(220, 232, 245, 255) The HoverItemColor default of ListBoxStyle.
DefaultListBoxPressedItemColor Color new(160, 190, 225, 255) The PressedItemColor default of ListBoxStyle.
DefaultListBoxSelectedItemColor Color new(190, 215, 240, 255) The SelectedItemColor default of ListBoxStyle.
DefaultListBoxItemHeight int 24 The ItemHeight default of ListBoxStyle: the row height of a Fixed list, in units.
DefaultComboBoxBackgroundColor Color Color.White The BackgroundColor default of ComboBoxStyle.
DefaultComboBoxToggleButtonWidth int 24 The width of the toggle button in the default ToggleButtonStyle of ComboBoxStyle, in units.
DefaultTreeViewSubItemsShift Margin (16, 0) The SubItemsShift default of TreeViewStyle: the indent of each level, in units.
DefaultSeparatorColor Color new(150, 150, 160, 255) The BackgroundColor default of every Separator, read when a separator is created.
DefaultGridLayoutColor Color new(255, 0, 0, 255) The LayoutColor of every Grid, read when a grid is created.
DefaultTimeBeforeShowToolTipMs int 500 The TimeBeforeShowMs default of ToolTipStyle.
DefaultToolTipBackgroundColor Color new(255, 255, 225, 255) The BackgroundColor default of ToolTipStyle.
DefaultToolTipMarginFromMouseCursor Margin (14, 14) The MarginFromMouseCursor default of ToolTipStyle, in units.
DefaultContextMenuBackgroundColor Color Color.White The background color of ContextMenuStyle’s default border.
DefaultContextMenuBorderColor Color new(80, 80, 80, 255) The border color of ContextMenuStyle’s default border.
DefaultContextMenuHighlightColor Color new(200, 220, 240, 255) The color of the hovered and selected rows of ContextMenuStyle’s default list style.
DefaultContextMenuIconColor Color new(80, 80, 80, 255) The color of the check and expand icons of ContextMenuStyle.
DefaultDoubleClickIntervalMs int 300 On use. The DoubleClickIntervalMs default of every element.
DefaultTimeBeforeRepeatStartsMs int 1000 On use. The TimeBeforeRepeatStartsMs default of every element.
DefaultTimeBetweenRepeatsMs int 300 On use. The TimeBetweenRepeatsMs default of every element.
DefaultMinDepth float 0 The MinDepth default of ViewPortStyle.
DefaultMaxDepth float 1 The MaxDepth default of ViewPortStyle.

The “on use” defaults apply to every element whose property has no value from code or a style, also to elements without a style class such as Grid. DefaultSeparatorColor and DefaultGridLayoutColor are read each time a separator or a grid is created.

Dependency properties

Every element property Foo is backed by FooDP, a DependencyProperty<T>. It holds the prioritized values (see value priority), runs the element’s reaction to a change, raises events, and can be bound or animated. An element creates FooDP the first time it is used: set, bound, subscribed to, or read through FooDP. Reading Foo doesn’t create it, so an element pays only for the properties it uses. Setting Foo is the same as FooDP.SetValue(value).

// the same as button.DesiredWidth = 120
button.DesiredWidthDP.SetValue(120);

// back to the style value
button.DesiredWidthDP.ClearValue(ValueSources.ManualAssign);

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, come when the value in effect changes: setting by hand the value a style already gives, or clearing a value that leaves the same value in effect, raises nothing. The first value a property gets is always raised, even if it equals the default. A value set at a lower priority than one already set is stored but changes nothing until the higher one is cleared.

The FooDP and Foo properties and the style classes are generated at build time by the BorrowedTorch.UIDPGenerator package from the .dpg file next to each element. How to add properties to an element of your own is on the base element page.

Setting a value

SetValue (and so setting Foo) goes through these steps:

  1. The element class’s own check, its OwnerPreAction (see DependencyPropertyActions<T>), may correct the value or reject it. For example, BaseElement clamps Transparency to 0 … 1 and keeps GridColumnSpan and GridRowSpan at 1 or more.
  2. The property’s PreAction, if you set one, gets the value the element already corrected (a Transparency of 3 arrives as 1). It doesn’t run for a value the element rejected, and it can correct or reject the value too.
  3. The value is stored for its source: set by hand, by the style override or by the general style. Setting the same value again for the same source stops here (unless checkForEquality is off).
  4. If a source of higher priority has a value, that one stays in effect and nothing else happens.
  5. If the value in effect changed, the element class’s own reaction runs, its OwnerPostAction (for example, the element is laid out again after a size change).
  6. Then the property’s PostAction, then OnPropertyChanged, and a binding that writes to its source passes the value on.

ClearValue skips the pre-actions: when the value in effect changes, steps 5 and 6 run with the value that takes over.

DependencyProperty<T> properties

Property Type Description
Value T Read-only. The value in effect: the one of the highest priority source, or the default when no source has one.
ValueSource ValueSources Read-only. The source the value in effect comes from, None when the property reads its default.
PreAction PreActionDelegate Called with (ref T value, ref bool canProceed) before every value is stored, from any source: change value to correct it, or set canProceed to false to reject it. It runs after the element class’s own check (its OwnerPreAction), so it gets the value the element already corrected, and it doesn’t run for a value the element rejected (see setting a value).
PostAction Action<T> Called with the new value in effect after the element class’s own reaction (its OwnerPostAction), only when the value in effect changes (see setting a value), before OnPropertyChanged.

DependencyProperty<T> events

Event Handler Raised when
OnPropertyChanged (T value) The value in effect changes. The handler gets the new value.
OnSourcePropertyChanged (object propertyValue) The bound Bindable source reports a change of the bound property (or of all properties, with an empty name). The handler gets the source property’s value, before conversion. Not raised for the echo of the property’s own write, nor in OneWayToSource mode.
OnSourceCollectionChanged (CollectionChangeType changeType, int startIndex, int count) The IBindableCollection held by the bound source property adds (Add) or removes (Remove) items. Not raised in OneWayToSource mode.

DependencyProperty<T> methods

Method Description
DependencyProperty(BaseElement owner, Action<T> postAction = null, PreActionDelegate preAction = null) Creates a stand-alone property owned by an element, with an optional post- and pre-action. Its default is default(T).
DependencyProperty(BaseElement owner, DependencyPropertyActions<T> actions) Creates a property that shares the element class’s actions and default; the generated FooDP properties use it.
SetValue(T value, bool checkForEquality = true, bool setSourceValue = true, ValueSources valueSource = ValueSources.ManualAssign) Stores the value for the source. With checkForEquality off, the same value raises the change again. With setSourceValue off, a bound source is not written.
ClearValue(ValueSources valueSource) Removes the value of that source. If it was the value in effect, the next source (or the default) takes over and the change is raised when the value differs.
Bind(object dataContext, string sourcePropertyName, BindingMode mode, IConverter converter = null) Binds the property to a public property of dataContext, replacing any earlier binding. See bindings.
Dispose() Removes the binding and the event handlers. The element calls it when it is disposed.

OwnerPreActionDelegate, with the signature (BaseElement owner, ref T value, ref bool canProceed, ValueSources valueSource), is the type of the element class’s own pre-action, FooDPActions.OwnerPreAction (see below).

DependencyPropertyActions<T>

What the properties of one name share over all the elements of a class: the class’s own pre- and post-action (set once, in its static constructor) and the default value. The generated code creates one per dependency property, as the static FooDPActions field of the element class.

Property Type Description
OwnerPreAction OwnerPreActionDelegate The element class’s own check of every value before it is stored, from any source: it may correct the value or reject it (canProceed). It runs before the property’s PreAction. Set it once, in the element class’s static constructor: a second set throws, so the actions of a class (the library’s elements’ too) can’t be replaced from outside.
OwnerPostAction Action<BaseElement, T> The element class’s own reaction to a new value in effect, with the element it runs for: before the property’s PostAction and OnPropertyChanged. Set once, like OwnerPreAction.
DefaultValue T Read-only. The value read while no source has one. Some defaults are read from DefaultSettings each time (see default settings).
Method Description
DependencyPropertyActions() Creates an empty set of actions with the default default(T).

Bindings

A dependency property can be bound to a public property of any object, the view model. When the object derives from Bindable and calls PropertyChangedInvoke, the element follows its changes. BindableCollection<T> is a list that tells a bound list box about added and removed items. This view model and converter are used by the example below:

// a view model: the elements bound to it follow its PropertyChangedInvoke calls
// (in a setter without a name for the setter's own property, with nameof for another)
public sealed class SettingsViewModel : Bindable
{
    private string _playerName = "";
    private float _volume = 0.5f;

    public string PlayerName
    {
        get => _playerName;
        set
        {
            _playerName = value;
            PropertyChangedInvoke();
            PropertyChangedInvoke(nameof(Greeting));
        }
    }

    public string Greeting => $"Welcome, {PlayerName}";

    public float Volume
    {
        get => _volume;
        set
        {
            _volume = value;
            PropertyChangedInvoke();
        }
    }

    // added and removed items reach a bound list
    public BindableCollection<string> Levels { get; } = [];
}

// turns the volume (0..1) into the text of a label
public sealed class PercentConverter : IConverter
{
    public object Convert(object value) => $"Volume {(float)value * 100:0} %";

    public object ConvertBack(object value) => throw new NotSupportedException();
}
A text box with Ash and the label Welcome, Ash beside it; a slider at 65 percent with the label Volume 65 %; a list with Forest, Desert and Caves
A text box, a slider and a list bound to one view model.
var settings = new SettingsViewModel();

var name = new RichTextBox("name")
{
    Type = RichTextBoxType.ReadWrite,
    DesiredWidth = 220,
    DesiredHeight = 30,
    TextMargin = (8, 0),
    VerticalTextAlignment = VerticalTextAlignment.Center,
    BackgroundColor = new Color(40, 31, 23),
    HorizontalAlignment = HorizontalAlignment.Left,
    VerticalAlignment = VerticalAlignment.Top,
    Margin = (16, 16)
};
var greeting = new Label
{
    HorizontalAlignment = HorizontalAlignment.Left,
    VerticalAlignment = VerticalAlignment.Top,
    Margin = (252, 22)
};
var volume = new Slider
{
    DesiredWidth = 220,
    DesiredHeight = 18,
    Max = 1,
    Margin = (16, 66)
};
var volumeText = new Label
{
    HorizontalAlignment = HorizontalAlignment.Left,
    VerticalAlignment = VerticalAlignment.Top,
    Margin = (252, 66)
};
var levels = new ListBox { DesiredWidth = 220, DesiredHeight = 90, Margin = (16, 100) };

name.TextDP.Bind(settings, nameof(settings.PlayerName), BindingMode.TwoWay);
greeting.TextDP.Bind(settings, nameof(settings.Greeting), BindingMode.OneWay);
volume.ValueDP.Bind(settings, nameof(settings.Volume), BindingMode.TwoWay);
volumeText.TextDP.Bind(settings, nameof(settings.Volume), BindingMode.OneWay,
    new PercentConverter());
levels.ItemsSourceDP.Bind(settings, nameof(settings.Levels), BindingMode.OneWay);

// changes of the view model reach the elements,
// and the edits of the user reach the view model
settings.PlayerName = "Ash";
settings.Volume = 0.65f;
settings.Levels.Add("Forest");
settings.Levels.Add("Desert");
settings.Levels.Add("Caves");

ui.AddElementToRoot(name);
ui.AddElementToRoot(greeting);
ui.AddElementToRoot(volume);
ui.AddElementToRoot(volumeText);
ui.AddElementToRoot(levels);

How a binding behaves:

  • Bind finds the source property by name. Unless the mode is OneWayToSource, it reads the source value right away; in OneWayToSource mode the source is first written at the element’s next change.
  • Values from the source are ManualAssign values. A source value of the property’s type is taken as it is, null clears a reference-type property, and any value becomes its ToString() for a string property. Other values are ignored. With a converter, Convert runs first and its result must have the property’s type (or be null).
  • Writing to the source (OneWayToSource, TwoWay) needs a writable source property. The value goes through ConvertBack when there is a converter, and is skipped when it can’t be assigned to the source property’s type.
  • The source’s notification of a two-way write is no change for the element, but a value the source changed on the way (clamped, for example) is taken. A notification without a new value raises nothing; a collection is taken again, since its items may have changed.
  • The view model and the bound collection reference the binding weakly: a bound element that is dropped without being disposed doesn’t stay alive because its view model does.

BindingMode

Value Meaning
OneWay Source to element.
OneWayToSource Element to source.
TwoWay Both ways.

Bindable

The abstract base of a view model.

Event Handler Raised when
OnPropertyChanged (string propertyName) The view model calls PropertyChangedInvoke. The handler gets the name of the property that changed; an empty (or null) name means every property changed.
Method Description
PropertyChangedInvoke(string propertyName = "") Protected. Raises OnPropertyChanged. Called from a property’s setter without a name, it names that property ([CallerMemberName]); another property is named with nameof. An empty or null name means every property changed: PropertyChangedInvoke(string.Empty) (with no argument outside a setter, it names the calling method instead).

BindableCollection<T>

A list that raises OnCollectionChanged for every change, so a bound ListBox, ComboBox, TreeView or ContextMenu updates only the changed rows. It implements IBindableCollection and IReadOnlyList<T>, and can be filled with a collection initializer or [].

Property Type Description
this[int index] T The item at the index. Setting it is reported as the old item removed and the new one added at that index.
Count int Read-only. The number of items.
IsReadOnly bool Read-only. Always false.
Event Handler Raised when
OnCollectionChanged (bool isItemsAdded, int startIndex, int count) Items are added (isItemsAdded is true) or removed, starting at startIndex.
Method Description
BindableCollection() Creates an empty collection.
Add(T item) Adds the item at the end.
AddRange(IEnumerable<T> collection) Adds the items at the end, reported as one change. Does nothing for null or an empty collection.
Insert(int index, T item) Inserts the item at the index. An index outside 0..Count is ignored.
InsertRange(int index, IEnumerable<T> collection) Inserts the items at the index, reported as one change. An index outside 0..Count is ignored.
Remove(T item) Removes the first occurrence of the item. Returns false when it is not in the collection.
RemoveAt(int index) Removes the item at the index. An index out of range is ignored.
RemoveRange(int index, int count) Removes up to count items from the index, reported as one change.
Clear() Removes every item, reported as one change.
TryGetElementAt(int index) Returns the item at the index, or default when the index is out of range.
Contains(T item) Whether the item is in the collection.
CopyTo(T[] array, int arrayIndex) Copies the items into the array from the index.
GetEnumerator() Enumerates the items.

IBindableCollection

An IEnumerable that reports its changes. Implement it for a collection of your own to use it as a bound items source.

Event Handler Raised when
OnCollectionChanged (bool isItemsAdded, int startIndex, int count) Items were added (true) or removed (false), count of them from startIndex.

CollectionChangeType

Passed to OnSourceCollectionChanged.

Value Meaning
Initialize The whole source is taken again. Used by the list box when it rebuilds its rows; OnSourceCollectionChanged doesn’t raise it.
Add Items were added.
Remove Items were removed.

IConverter

Translates between the source’s type and the property’s type.

Method Description
Convert(object value) Turns a source value into the property’s value. Used in OneWay and TwoWay mode.
ConvertBack(object value) Turns the property’s value into a source value. Used in OneWayToSource and TwoWay mode.

Items templates

A list box, combo box, tree view or context menu with an ItemsSource makes one row per source object. Its ItemsTemplate makes the element shown in each row; without one, the row shows the object’s ToString() in a Label. The elements a template makes belong to the list, which may dispose or reuse them, so don’t keep or move them. Setting another template on a list box with an items source rebuilds its rows. The template below binds each row’s check box to its quest, so the row follows the quest and the quest follows the row:

// a quest that tells its bound elements when it is done or not
public sealed class Quest(string title, bool done) : Bindable
{
    private bool _done = done;

    public string Title { get; } = title;

    public bool Done
    {
        get => _done;
        set
        {
            _done = value;
            PropertyChangedInvoke();
        }
    }
}

// makes the element of a row from its source object
public sealed class QuestTemplate : IItemsTemplate
{
    public BaseElement GenerateItemElement(object data)
    {
        var quest = (Quest)data;

        var checkBox = new CheckBox
        {
            Text = quest.Title,
            DesiredHeight = 22,
            Margin = (6, 3),
            HorizontalAlignment = HorizontalAlignment.Left,
            VerticalAlignment = VerticalAlignment.Top
        };

        // both ways: the box shows Done, and a click on the box sets Done
        checkBox.CheckedDP.Bind(quest, nameof(Quest.Done), BindingMode.TwoWay);

        return checkBox;
    }
}
A list of four check boxes: Light the beacon and Rest by the fire checked, Find the map and Cross the river unchecked
Each quest of the source shown as a check box bound to its Done: the last quest was added not done, and setting its Done checked its box.
var quests = new BindableCollection<Quest>
{
    new("Light the beacon", true),
    new("Find the map", false),
    new("Cross the river", false)
};

var list = new ListBox("quests")
{
    DesiredWidth = 300,
    DesiredHeight = 120,
    Margin = 16,
    ItemsTemplate = new QuestTemplate(),     // one row element per quest
    ItemsSource = quests
};

var rest = new Quest("Rest by the fire", false);

quests.Add(rest);    // a new row appears, its box not checked
rest.Done = true;    // the box checks itself

ui.AddElementToRoot(list);

IItemsTemplate

A list’s ItemsTemplate. A virtualized ListBox (VirtualizationMode Fixed) reuses the rows that scroll out of view: a template that can show another source object in an element it made overrides UpdateItemElement, otherwise a reused row gets a new element, as without virtualization.

Method Description
GenerateItemElement(object data) Returns a new element that shows the source object.
UpdateItemElement(BaseElement element, object data) Returns the element that shows data in a row whose element, made by this template, showed another source object: element updated, or a new one, which replaces it (the list disposes the replaced one). By default it returns GenerateItemElement(data).
// updates the label it made instead of making a new one
public class LevelTemplate : IItemsTemplate
{
    public BaseElement GenerateItemElement(object data) =>
        new Label { Text = (string)data, Margin = 5 };

    public BaseElement UpdateItemElement(BaseElement element, object data)
    {
        ((Label)element).Text = (string)data;

        return element;
    }
}

Animations

An Animation<T> drives one or more targets of type T along a time line of durationMs: dependency properties, or any other property through its setter (see setter targets). Frames describe the values: SmoothAnimationFrame<T> goes from one value to another over a stretch of the time line, DiscreteAnimationFrame<T> sets a value at a point of it. Start runs the animation and adds it to the UI’s animations, which the UI advances on every Update.

Two columns, Smooth frames and Discrete frames, each with the banner Level complete sliding in and a progress bar filling: on the left both move evenly, on the right they jump in steps, and the banner's color fades on the left and blinks on the right
The same animations with smooth frames (left) and with discrete frames at points of the same time lines (right).
var grid = new Grid
{
    DesiredWidth = 460,
    DesiredHeight = 100,
    HorizontalAlignment = HorizontalAlignment.Left,
    VerticalAlignment = VerticalAlignment.Top,
    Margin = 16
};
grid.AddColumnDefinition(1.0f);
grid.AddColumnDefinition(1.0f);
grid.AddRowDefinition(1.0f);

// the same banner and bar in each column (a grid cell clips them, so a banner
// slides in from the left edge of its own column)
(Label Banner, ProgressBar Bar) Example(int column, string title)
{
    var banner = new Label
    {
        Text = "Level complete",
        FontSize = 22,
        GridColumn = column,
        HorizontalAlignment = HorizontalAlignment.Left,
        VerticalAlignment = VerticalAlignment.Top,
        Margin = (-220, 28)
    };
    var bar = new ProgressBar
    {
        DesiredWidth = 200,
        DesiredHeight = 12,
        Max = 100,
        GridColumn = column,
        HorizontalAlignment = HorizontalAlignment.Left,
        VerticalAlignment = VerticalAlignment.Top,
        Margin = (0, 78)
    };

    grid.AddItem(new Label
    {
        Text = title,
        GridColumn = column,
        HorizontalAlignment = HorizontalAlignment.Left,
        VerticalAlignment = VerticalAlignment.Top
    });
    grid.AddItem(banner);
    grid.AddItem(bar);

    return (banner, bar);
}

var smooth = Example(0, "Smooth frames");
var discrete = Example(1, "Discrete frames");

ui.AddElementToRoot(grid);

// one animation of a property, started at once (Start adds it to the UI's animations)
void Animate<T>(DependencyProperty<T> property, int durationMs, bool pulse,
    params BaseAnimationFrame<T>[] frames)
{
    var animation = pulse
        ? new Animation<T>(durationMs, AnimationRepeatType.Infinite,
            autoReverse: true, deleteOnComplete: false)
        : new Animation<T>(durationMs);

    foreach (var frame in frames) animation.AddFrame(frame);

    animation.AddDependencyProperty(property);
    animation.Start();
}

var gold = new Color(233, 194, 122);
var flame = new Color(242, 140, 40);

// smooth frames: from one value to another over a stretch of the time line
Animate(smooth.Banner.MarginDP, 500, false,
    new SmoothAnimationFrame<Margin>((-220, 28), (0, 28), 500,
        shapingFunction: new CubicEaseOut()));
Animate(smooth.Bar.ValueDP, 1000, false, new SmoothAnimationFrame<float>(0, 100, 1000));
Animate(smooth.Banner.ForegroundColorDP, 400, true,
    new SmoothAnimationFrame<Color>(gold, flame, 400));

// discrete frames: a value at a point of the time line, kept until the next one
Animate(discrete.Banner.MarginDP, 500, false,
    new DiscreteAnimationFrame<Margin>((-220, 28), 0),
    new DiscreteAnimationFrame<Margin>((-110, 28), 125),
    new DiscreteAnimationFrame<Margin>((-45, 28), 250),
    new DiscreteAnimationFrame<Margin>((-10, 28), 375),
    new DiscreteAnimationFrame<Margin>((0, 28), 500));
Animate(discrete.Bar.ValueDP, 1000, false,
    new DiscreteAnimationFrame<float>(0, 0),
    new DiscreteAnimationFrame<float>(25, 250),
    new DiscreteAnimationFrame<float>(50, 500),
    new DiscreteAnimationFrame<float>(75, 750),
    new DiscreteAnimationFrame<float>(100, 1000));
Animate(discrete.Banner.ForegroundColorDP, 400, true,
    new DiscreteAnimationFrame<Color>(gold, 0),
    new DiscreteAnimationFrame<Color>(flame, 200));

The UI advances its running animations on every Update, by the frame’s elapsed game time. A long frame doesn’t skip boundaries: the animation still turns around, ends its runs and lands on the exact end values.

  • A run goes once along the time line, or forth and back with autoReverse. AnimationRepeatType.None plays one run, NumberOfTimes plays repeatsNumber runs, Infinite repeats until you pause or stop it.
  • When it completes, the animation applies the values of the end of its time line (its start, with autoReverse), then RunBoundaryValues.EndValue if it has one. With deleteOnComplete (the default) it is then removed from the UI’s animations; after a Reset, Start plays it again and adds it back.
  • Animated values of dependency properties are ManualAssign values: they win over styles and stay after the animation, completed or stopped. Clear them with FooDP.ClearValue(ValueSources.ManualAssign) to give the property back to its style.
  • A smooth frame blends int, float, double, Color, Margin, Point, Vector2 and Rectangle values by itself, rounding the whole numbers (an int, the sides of a Margin, the coordinates of a Point or a Rectangle, the channels of a Color). A smooth frame of any other type keeps From until the end of the frame, then switches to To, unless it is given a blend of its own (see blends of your own).
  • An animation whose targets all belong to disposed elements is removed automatically.

Setter targets

AddDependencyProperty adds a dependency property as a target. AddTarget adds anything else a value can be given to, through a setter: a property that is no dependency property, or a value of your own that your drawing reads. The setter gets each value, as a dependency property would. The element passed with it is the one the value belongs to: once every target of an animation belongs to a disposed element, the UI lets go of the animation, as it does for dependency properties. Pass null for a value that belongs to no element; such a target never counts as disposed, so stop its animation yourself when you are done with it.

// a value of your own that a view port draws with (see the view port on the
// images page): no property of an element, so the animation sets it through a setter
var angle = 0f;
var scene = new ViewPort("scene") { DesiredWidth = 280, DesiredHeight = 168 };
scene.DrawInstructions = () => DrawLogo(angle);   // DrawLogo stands for your drawing code
ui.AddElementToRoot(scene);

var spin = new Animation<float>(4000, AnimationRepeatType.Infinite);
spin.AddFrame(new SmoothAnimationFrame<float>(0, MathHelper.TwoPi, 4000));
spin.AddTarget(scene, value => angle = value);    // let go of once the view port is disposed
spin.Start();

Blends of your own

A smooth frame of a type it doesn’t blend by itself, such as Vector3, takes a Blend of its own. It gets From, To and the share of the way between them (0 at From, 1 at To, past them under a shaping function that overshoots), and returns the value there. Given, it is used for the types the frame blends by itself as well.

// MonoGame's Vector3.Lerp has the shape of a blend: (from, to, amount)
var rise = new SmoothAnimationFrame<Vector3>(Vector3.Zero, new Vector3(0, 10, 0), 500)
{
    Blend = Vector3.Lerp
};

Starting, stopping and seeking

Start adds the animation to the UI’s animations when it isn’t there yet, so BorrowedTorchUI.AddAnimation is needed only to register an animation that you start later (before 2.1.0, every animation had to be added first). Stop is its counterpart, for an animation you are done with before its elements are: it takes the animation out of the UI’s animations and puts it back to not started, at the start of its time line. The values it set stay, and the next Start runs it from the beginning. Pause keeps the animation where it is, and Reset puts it back to not started; neither takes it out of the UI’s animations.

Seek(int positionMs) puts the time line at a moment, in milliseconds from its start (kept between 0 and DurationMs), and gives the targets the values the animation has there, as a run going forward shows them, whatever they showed before:

  • The smooth frames are taken in the order they start: each one the moment is past gives its end value, and the one the moment is in gives its value there. Before the start of every smooth frame, the first one gives its start value.
  • Of the discrete frames, the latest one at or before the moment gives its value.
  • RunBoundaryValues are not applied.

A running animation goes on from there, forward. One that isn’t running (not started, paused or completed) is paused there, and Start goes on from it, so a seek before the first start skips StartValue. PositionMs tells where the time line is. Together they let a tool show any moment of an animation:

// a slider that shows any moment of the spin above
spin.Pause();

var scrubber = new Slider
{
    DesiredWidth = 200,
    DesiredHeight = 18,
    Max = spin.DurationMs,
    Value = spin.PositionMs
};
scrubber.OnValueChanged += (sender, value) => spin.Seek((int)value);

ui.AddElementToRoot(scrubber);

Animation<T>

An animation of properties of type T. It has the properties of BaseAnimation.

Property Type Description
State AnimationState Read-only. Where the animation is: not started, running, paused or completed.
RunBoundaryValues RunBoundaryValues<T> Read-only. The values applied when the animation starts and when it completes, or null.
Method Description
Animation(int durationMs, AnimationRepeatType repeatType = AnimationRepeatType.None, bool autoReverse = false, bool deleteOnComplete = true, RunBoundaryValues<T> runBoundaryValues = null, uint repeatsNumber = 1) Creates an animation with a time line of durationMs milliseconds. repeatsNumber counts the runs of a NumberOfTimes animation. A duration of 0 or less completes at once with the end values.
AddFrame(BaseAnimationFrame<T> frame) Adds a smooth or discrete frame.
AddDependencyProperty(DependencyProperty<T> property) Adds a property the animation drives. One animation can drive several properties.
AddTarget(BaseElement owner, Action<T> set) Adds a target set through a setter: set gets each value, as a dependency property would. owner is the element the value belongs to, null for none; an animation whose targets all belong to disposed elements is let go of. Throws an ArgumentNullException when set is null. See setter targets.
Start() Runs a not started or paused animation and adds it to the UI’s animations if it isn’t there, so AddAnimation isn’t needed first. Started from not started (the first time, or after Stop or Reset), it applies RunBoundaryValues.StartValue, then the values of the time line’s start, so a frame that applies at 0 ms replaces StartValue at once. Does nothing on a completed animation (call Reset first) or on a NumberOfTimes animation with 0 repeats.
Pause() Pauses a running animation; Start continues it.
Seek(int positionMs) Puts the time line at positionMs (kept between 0 and DurationMs) and gives the targets the values there, as a run going forward shows them. A running animation goes on from there; one that isn’t running is paused there. See seeking.
Stop() Takes the animation out of the UI’s animations and puts it back to not started, at the start of its time line; the values it set stay. Start runs it again from the beginning.
Reset() Puts the animation back to not started, at the start of its time line with its repeats restored. The properties keep their current values, and the animation stays among the UI’s animations.

BaseAnimation

The abstract base of animations, the type AddAnimation takes. Its properties other than State and PositionMs are set by the constructor.

Property Type Description
State AnimationState Read-only. The state of the animation.
DurationMs int Read-only. The length of the time line in milliseconds.
PositionMs int Read-only. Where the time line is, in milliseconds from its start. It goes back toward 0 while an auto reversing run goes back.
RepeatType AnimationRepeatType Read-only. How the runs repeat.
RepeatsNumber uint Read-only. The number of runs of a NumberOfTimes animation.
AutoReverse bool Read-only. Whether a run goes forth and back along the time line.
DeleteOnComplete bool Read-only. Whether the UI removes the animation when it completes.

AnimationState

Value Meaning
NotStarted Created or reset, not started yet.
Running Advancing with every update.
Paused Stopped where it was; Start continues it.
Completed All runs are done; Reset makes it playable again.

AnimationRepeatType

Value Meaning
None One run.
NumberOfTimes RepeatsNumber runs.
Infinite Runs until paused or removed.

BaseAnimationFrame<T>

The abstract base of the frames an Animation<T> takes. It has no public members; use SmoothAnimationFrame<T> or DiscreteAnimationFrame<T>.

SmoothAnimationFrame<T>

Goes from From to To between StartAtMs and StartAtMs + DurationMs of the time line, and goes back the same way when the time line reverses. Before its start it sets nothing. A shaping function bends the progress: pass any BaseShapingFunction from the BorrowedTorch.ShapingFunctions package, such as new CubicEaseOut(), or create one with ShapingFunctionFactory.Create(ShapingFunctionId.CubicEaseInOut).

Property Type Description
From T Read-only. The value at the start of the frame.
To T Read-only. The value at the end of the frame.
DurationMs int Read-only. The length of the frame in milliseconds.
StartAtMs int Read-only. Where the frame starts on the time line, in milliseconds.
ShapingFunction BaseShapingFunction Read-only. The function that maps the frame’s progress (0 to 1) to the share of the way from From to To. Linear when none is given.
Blend Func<T, T, float, T> Init-only. The value between From and To at a share of the way (0 at From, 1 at To, past them under a shaping function that overshoots), for a type the frame doesn’t blend by itself. int, float, double, Color, Margin, Point, Vector2 and Rectangle are blended without one; any other type switches from From to To at the frame’s end. Given, it is used for every type. null by default.
Method Description
SmoothAnimationFrame(T from, T to, int durationMs, int startAtMs = 0, BaseShapingFunction shapingFunction = null) Creates the frame.

DiscreteAnimationFrame<T>

Sets Value when the time line reaches ApplyAtMs. The discrete frames of an animation form one track: the value in effect is the one of the latest frame at or before the time line’s position, going forth and back alike. Of frames at the same time, the one added last wins.

Property Type Description
Value T Read-only. The value the frame sets.
ApplyAtMs int Read-only. The point of the time line where it is set, in milliseconds.
Method Description
DiscreteAnimationFrame(T value, int applyAtMs) Creates the frame.

RunBoundaryValues<T>

Values set on the animated properties outside the frames: StartValue when the animation first starts, EndValue when it completes. Pass it to the Animation<T> constructor.

  • Both values are always applied: one you don’t set is default(T), such as 0 or a transparent Color.
  • StartValue is applied before the values of the time line’s start, so a frame that applies at 0 ms replaces it at once. It shows only until the first frame begins (a discrete frame with applyAtMs above 0, a smooth frame with startAtMs above 0): use it to hold a value through a delay.
  • EndValue is applied after the end values of the frames and stays. An Infinite animation never completes, so it never applies EndValue.
Property Type Description
StartValue T The value set when the animation starts from not started, before the values of the time line’s start: a frame that applies at 0 ms replaces it at once.
EndValue T The value set after the end values of the frames when the animation completes. Never applied by an Infinite animation, which doesn’t complete.
Method Description
RunBoundaryValues() Creates the values, both default(T).

BorrowedTorchUI animation methods

Method Description
AddAnimation(BaseAnimation animation) Registers the animation so the UI advances it while it runs, without starting it. Start registers it as well, so this is needed only for an animation you start later. Adding it again while registered, or adding null, does nothing.
RemoveAnimation(BaseAnimation animation) Stops advancing the animation. It keeps its state; adding it again continues it. Stop takes an animation out as well, and puts it back at its start.