View Deep Dive
View is the base class for all visible UI elements in Terminal.Gui. View provides core functionality for layout, drawing, input handling, navigation, and scrolling. All interactive controls, windows, and dialogs derive from View.
See the Views Overview for a catalog of all built-in View subclasses.
Table of Contents
- View Hierarchy
- View Composition
- Core Concepts
- View Lifecycle
- Subsystems
- Common View Patterns
- Runnable
View Hierarchy
Terminology
- View - The base class for all visible UI elements
- SubView - A View that is contained in another View and rendered as part of the containing View's content area. SubViews are added via
Add() - SuperView - The View that contains SubViews. Each View has a
SuperViewproperty that references its container - Child View - A view that holds a reference to another view in a parent/child relationship (used sparingly; generally SubView/SuperView is preferred)
- Parent View - A view that holds a reference to another view but is NOT a SuperView (used sparingly)
Key Properties
SubViews- Read-only list of all SubViews added to this ViewSuperView- The View's container (null if the View has no container)Id- Unique identifier for the View (should be unique among siblings)Data- Arbitrary data attached to the ViewApp- The application context this View belongs toDriver- The driver used for rendering (derived from App). This is a shortcut toApp.Driverfor convenience.
View Composition
Views are composed of several nested layers that define how they are positioned, drawn, and scrolled:
View Composition Diagram
classDiagram
class View {
+Frame: Rectangle
+Margin: Adornment - outermost
+Border: Adornment - border lines and Title
+Padding: Adornment - innermost - Scrollbars
+Viewport: Rectangle describing portal into ContentArea
+ContentArea: Rectangle with Location always 0,0
+GetContentSize(): Size
+SetContentSize(Size)
}
class Adornment {
+Thickness: Thickness
}
class Thickness {
+Top: int
+Right: int
+Bottom: int
+Left: int
}
class Rectangle {
+Location: Point
+Size: Size
}
View --> Adornment : has
Adornment --> Thickness : has
View --> Rectangle : has
note for View "Frame defines location and size relative to SuperView"
note for Adornment "Separates Frame from Viewport"
note for Rectangle "Defines location and size"
The diagram above shows the structure of a View's composition:
- Frame: The outermost rectangle defining the View's location and size
- Margin: Separates the View from other SubViews
- Border: Contains visual border and title
- Padding: Offsets the Viewport from the Border
- Viewport: The visible portion of the Content Area
- Content Area: Where the View's content is drawn (shown larger than Viewport to illustrate scrolling)
Each layer is defined by a Thickness that specifies the width of each side (top, right, bottom, left). The Content Area is shown as a separate container that the Viewport "looks into" - this illustrates how scrolling works. In this example, the Viewport is positioned at (5,5) relative to the Content Area, showing how scrolling works.
The Layers
Frame- The outermost rectangle defining the View's location and size relative to the SuperView's content area- Margin - Adornment that provides spacing between the View and other SubViews
- Border - Adornment that draws the visual border and title
- Padding - Adornment that provides spacing between the border and the viewport
Viewport- Rectangle describing the visible portion of the content area- Content Area - The total area where content can be drawn (defined by
GetContentSize())
See the Layout Deep Dive for complete details on View composition and layout.
Core Concepts
Frame vs. Viewport
- Frame - The View's location and size in SuperView-relative coordinates. Frame includes all adornments (Margin, Border, Padding)
- Viewport - The visible "window" into the View's content, located inside the adornments. Viewport coordinates are always relative to (0,0) of the content area
// Frame is SuperView-relative
view.Frame = new Rectangle (10, 5, 50, 20);
// Viewport is content-relative (the visible portal)
view.Viewport = new Rectangle (0, 0, 45, 15); // Adjusted for adornments
Content Area and Scrolling
The Content Area is where the View's content is drawn. By default, the content area size matches the Viewport size. To enable scrolling:
- Call
SetContentSize()with a size larger than the Viewport - Change
Viewport.Locationto scroll the content
See the Scrolling Deep Dive for complete details.
Adornments
Adornments are special Views that surround the content:
- Margin - Transparent spacing outside the Border
- Border - Visual frame with LineStyle, title, and arrangement UI
- Padding - Spacing inside the Border, outside the Viewport
Each adornment has a Thickness that defines the width of each side (Top, Right, Bottom, Left).
See the Layout Deep Dive for complete details on adornments.
View Lifecycle
Initialization
Views implement ISupportInitializeNotification:
- Constructor - Creates the View and sets up default state
BeginInit()- Signals initialization is startingEndInit()- Signals initialization is complete; raisesInitializedeventIsInitialized- Property indicating if initialization is complete
During initialization, App is set to reference the application context, enabling views to access application services like the driver and current session.
Disposal
Views are IDisposable:
- Call
Dispose()to clean up resources - The
Disposingevent is raised when disposal begins - Automatically disposes SubViews, adornments, and scroll bars
Subsystems
View is organized as a partial class across multiple files, each handling a specific subsystem:
Commands
See the Command Deep Dive.
- View.AddCommand - Declares commands the View supports
- View.InvokeCommand - Invokes a command
- Command enum - Standard set of commands (Accept, Activate, HotKey, etc.)
CommandsToBubbleUp- Opt-in list of commands that bubble from SubViews to this View- View.DispatchDown - Dispatches a command downward to a SubView with bubbling suppressed (inverse of
TryBubbleToSuperView) DefaultAcceptView- The SubView that receives Accept when no other SubView handles it
Input Handling
Keyboard
See the Keyboard Deep Dive.
- KeyBindings - Maps keys to Commands
- HotKey - The hot key for the View
HotKeySpecifier- Character used to denote hot keys in text (default: '_')- Events:
KeyDown,InvokingKeyBindings
Mouse
See the Mouse Deep Dive.
- MouseBindings - Maps mouse events to Commands
MouseHoldRepeat- Enables continuous button press events- View.Highlight event - Event for visual feedback on mouse hover/click
- View.HighlightStyle - Visual style when highlighted
- Events:
MouseEnter,MouseLeave,MouseEvent
Layout and Arrangement
See the Layout Deep Dive and Arrangement Deep Dive.
Position and Size
X- Horizontal position using PosY- Vertical position using PosWidth- Width using DimHeight- Height using Dim
Layout Features
Dim.Auto()- Automatic sizing based on contentPos.AnchorEnd()- Anchor to right/bottom edges- Pos.Align - Align views relative to each other
- Pos.Center - Center within SuperView
- Dim.Fill - Fill available space
Arrangement
Arrangement- Controls if View is movable/resizable- ViewArrangement - Flags: Fixed, Movable, Resizable, Overlapped
Events
LayoutStarted- Before layout beginsLayoutComplete- After layout completesFrameChanged- When Frame changesViewportChanged- When Viewport changes
Drawing
See the Drawing Deep Dive.
Color and Style
- View.Scheme - Color scheme for the View
- View.SetAttribute - Sets the attribute for subsequent drawing
- View.SetAttributeForRole - Sets attribute based on VisualRole
See the Scheme Deep Dive for details on color theming.
Drawing Methods
- View.Draw - Main drawing method
- View.AddRune - Draws a single Rune
- View.AddStr - Draws a string
- View.Move - Positions the Draw Cursor (internal rendering position, NOT the visible Terminal Cursor)
- View.Clear - Clears the View's content
Warning
Move() sets the Draw Cursor (where next character renders), NOT the Terminal Cursor (visible cursor indicator).
To position the Terminal Cursor, use the View.Cursor property. See Cursor Management for details.
Drawing Events
DrawingContent- Before content is drawnDrawingContentComplete- After content is drawnDrawingAdornments- Before adornments are drawnDrawingAdornmentsComplete- After adornments are drawn
Invalidation
- View.SetNeedsDraw - Marks View as needing redraw
- View.NeedsDraw - Property indicating if View needs redraw
Navigation
See the Navigation Deep Dive.
- CanFocus - Whether the View can receive keyboard focus
- HasFocus - Whether the View currently has focus
- TabStop - TabBehavior for tab navigation
- View.ZOrder - Order in tab navigation
- View.SetFocus - Gives focus to the View
Events:
HasFocusChanging- Before focus changes (cancellable)HasFocusChanged- After focus changes- Accepting - When Accept is invoked (typically Enter key) - cancellable
- Accepted - After Accept completes
- Activating - When Activate is invoked (typically Space or mouse click) - cancellable
- Activated - After Activate completes
- HandlingHotKey - When HotKey is invoked (the view's HotKey was pressed) - cancellable
- HotKeyCommand - After HotKey completes
Scrolling
See the Scrolling Deep Dive.
Viewport- Visible portion of the content areaGetContentSize()- Returns size of scrollable contentSetContentSize()- Sets size of scrollable contentScrollHorizontal()- Scrolls content horizontallyScrollVertical()- Scrolls content verticallyVerticalScrollBar- Built-in vertical scrollbarHorizontalScrollBar- Built-in horizontal scrollbarViewportSettings- ViewportSettingsFlags controlling scroll behavior
Text
Text- The View's text contentTitle- The View's title (shown in Border)TextFormatter- Handles text formatting and alignmentTextDirection- Text direction (LeftRight, RightToLeft, TopToBottom)TextAlignment- Text alignment (Left, Centered, Right, Justified)VerticalTextAlignment- Vertical alignment (Top, Middle, Bottom, Justified)
View Lifecycle
1. Creation
View view = new ()
{
X = Pos.Center (),
Y = Pos.Center (),
Width = Dim.Percent (50),
Height = Dim.Fill ()
};
2. Initialization
When a View is added to a SuperView or when Application.Run is called:
BeginInit()is calledEndInit()is calledIsInitializedbecomes true- Initialized event is raised
3. Layout
Layout happens automatically when needed:
- View.SetNeedsLayout marks View as needing layout
- View.Layout calculates position and size
LayoutStartedevent is raised- Frame and Viewport are calculated based on X, Y, Width, Height
- SubViews are laid out
LayoutCompleteevent is raised
4. Drawing
Drawing happens automatically when needed:
- View.SetNeedsDraw marks View as needing redraw
- View.Draw renders the View
DrawingContentevent is raised- View.OnDrawingContent is called (override to draw custom content)
DrawingContentCompleteevent is raised- Adornments are drawn
- SubViews are drawn
5. Input Processing
Input is processed in this order:
- Keyboard: Key → KeyBindings → Command → Command Handlers → Events
- Mouse: MouseEvent → MouseBindings → Command → Command Handlers → Events
6. Disposal
view.Dispose ();
- Raises View.Disposing event
- Disposes adornments, scrollbars, SubViews
- Cleans up event handlers and resources
Subsystems
Commands
See the Command Deep Dive for complete details.
Views use a command pattern for handling input:
// Add a command the view supports
view.AddCommand (Command.Accept, () =>
{
// Handle the Accept command
return true;
});
// Bind a key to the command
view.KeyBindings.Add (Key.Enter, Command.Accept);
// Bind a mouse action to the command
view.MouseBindings.Add (MouseFlags.LeftButtonClicked, Command.Activate);
// Enable command bubbling from SubViews to this View
view.CommandsToBubbleUp = [Command.Accept, Command.Activate];
// Set the default view that receives Accept when no other SubView handles it
// (typically a Button with IsDefault = true, found automatically via IAcceptTarget)
view.DefaultAcceptView = okButton;
Input
Keyboard
See the Keyboard Deep Dive for complete details.
The keyboard subsystem processes key presses through:
- View.KeyDown event (cancellable)
- View.OnKeyDown virtual method
- KeyBindings - Converts keys to commands
- Command handlers (registered via View.AddCommand)
Mouse
See the Mouse Deep Dive for complete details.
The mouse subsystem processes mouse events through:
- View.MouseEvent event (low-level)
- View.OnMouseEvent virtual method
- View.MouseEnter / View.MouseLeave events
- View.MouseBindings - Converts mouse actions to commands
- Command handlers
Layout
See the Layout Deep Dive for complete details.
Layout is declarative using Pos and Dim:
Label label = new () { Text = "Name:" };
TextField textField = new ()
{
X = Pos.Right (label) + 1,
Y = Pos.Top (label),
Width = Dim.Fill ()
};
The layout system automatically:
- Calculates Frame based on X, Y, Width, Height
- Handles Adornment thickness
- Calculates Viewport
- Lays out SubViews recursively
Drawing
See the Drawing Deep Dive for complete details.
Views draw themselves using viewport-relative coordinates:
protected override bool OnDrawingContent ()
{
// Draw at viewport coordinates (0,0)
Move (0, 0);
SetAttribute (new Attribute (Color.White, Color.Blue));
AddStr ("Hello, Terminal.Gui!");
return true;
}
Key drawing concepts:
- LineCanvas - For drawing lines with auto-joining
- Attribute - Color and text style
- TextStyle - Bold, Italic, Underline, etc.
- Gradient / GradientFill - Color gradients
Navigation
See the Navigation Deep Dive for complete details.
Navigation controls keyboard focus movement:
- CanFocus - Whether View can receive focus
- TabStop - TabBehavior (NoStop, TabStop, TabGroup)
- View.TabIndex - Tab order within SuperView
- View.SetFocus - Requests focus
- View.AdvanceFocus - Moves focus to next/previous View
Scrolling
See the Scrolling Deep Dive for complete details.
Scrolling is built into every View:
// Set content size larger than viewport
view.SetContentSize(new Size(100, 100));
// Scroll the content
view.Viewport = view.Viewport with { Location = new Point(10, 10) };
// Or use helper methods
view.ScrollVertical(5);
view.ScrollHorizontal(3);
// Enable scrollbars
view.ViewportSettings |= ViewportSettingsFlags.HasVerticalScrollBar;
view.ViewportSettings |= ViewportSettingsFlags.HasHorizontalScrollBar;
Common View Patterns
Creating a Custom View
public class MyCustomView : View
{
public MyCustomView ()
{
// Set up default size
Width = Dim.Auto ();
Height = Dim.Auto ();
// Can receive focus
CanFocus = true;
// Add supported commands
AddCommand (Command.Accept, HandleAccept);
// Configure key bindings
KeyBindings.Add (Key.Enter, Command.Accept);
}
protected override bool OnDrawingContent ()
{
// Draw custom content using viewport coordinates
Move (0, 0);
SetAttributeForRole (VisualRole.Normal);
AddStr ("My custom content");
return true; // Handled
}
private bool HandleAccept ()
{
// Handle the Accept command
// Raise events, update state, etc.
return true; // Handled
}
}
Adding SubViews
View container = new ()
{
Width = Dim.Fill (),
Height = Dim.Fill ()
};
Button leftButton = new () { Text = "OK", X = 2, Y = 2 };
Button middleButton = new () { Text = "Cancel", X = Pos.Right (leftButton) + 2, Y = 2 };
container.Add (leftButton, middleButton);
Using Adornments
View view = new ()
{
BorderStyle = LineStyle.Double,
Title = "My View"
};
// Configure border
view.Border.Thickness = new Thickness (1);
view.Border.Settings = BorderSettings.Title;
// Add padding
view.Padding.Thickness = new Thickness (1);
// Add margin
view.Margin.Thickness = new Thickness (2);
Implementing Scrolling
View view = new ()
{
Width = 40,
Height = 20
};
// Set content larger than viewport
view.SetContentSize (new Size (100, 100));
// Enable scrollbars with automatic visibility
view.ViewportSettings |= ViewportSettingsFlags.HasVerticalScrollBar;
view.ViewportSettings |= ViewportSettingsFlags.HasHorizontalScrollBar;
// Add key bindings for scrolling
view.KeyBindings.Add (Key.CursorUp, Command.ScrollUp);
view.KeyBindings.Add (Key.CursorDown, Command.ScrollDown);
view.KeyBindings.Add (Key.CursorLeft, Command.ScrollLeft);
view.KeyBindings.Add (Key.CursorRight, Command.ScrollRight);
// Add command handlers
view.AddCommand (Command.ScrollUp, () => { view.ScrollVertical (-1); return true; });
view.AddCommand (Command.ScrollDown, () => { view.ScrollVertical (1); return true; });
Runnable Views
Views can implement IRunnable to run as independent, blocking sessions with typed results. This decouples runnability from inheritance, allowing any View to participate in session management.
IRunnable Architecture
The IRunnable pattern provides:
- Interface-Based: Implement
IRunnable<TResult>instead of inheriting fromRunnable - Type-Safe Results: Generic
TResultparameter for compile-time type safety - Fluent API: Chain
Init(),Run(), andShutdown()for concise code - Automatic Disposal: Framework manages lifecycle of created runnables
- CWP Lifecycle Events:
IsRunningChanging/Changed,IsModalChanging/Changed
Creating a Runnable View
Derive from Runnable
public class ColorPickerDialog : Runnable<Color?>
{
private ColorPicker16 _colorPicker;
public ColorPickerDialog ()
{
Title = "Select a Color";
_colorPicker = new ColorPicker16 { X = Pos.Center (), Y = 2 };
Button okButton = new () { Text = "OK", IsDefault = true };
okButton.Accepting += (_, e) =>
{
Result = _colorPicker.SelectedColor;
Application.RequestStop ();
};
Add (_colorPicker, okButton);
}
}
Running with Fluent API
The fluent API enables elegant, concise code with automatic disposal:
// Framework creates, runs, and disposes the runnable automatically
Color? result = Application.Create ()
.Init ()
.Run<ColorPickerDialog> ()
.Shutdown () as Color?;
if (result is { })
{
Console.WriteLine($"Activated: {result}");
}
Running with Explicit Control
For more control over the lifecycle:
IApplication app = Application.Create ();
app.Init ();
ColorPickerDialog dialog = new ();
app.Run (dialog);
// Extract result after Run returns
Color? result = dialog.Result;
// Caller is responsible for disposal
dialog.Dispose ();
app.Shutdown ();
Disposal Semantics
"Whoever creates it, owns it":
Run<TRunnable>(): Framework creates → Framework disposes (inShutdown())Run(IRunnable): Caller creates → Caller disposes
Result Extraction
Extract the result in OnIsRunningChanging when stopping:
protected override bool OnIsRunningChanging (bool oldIsRunning, bool newIsRunning)
{
if (!newIsRunning) // Stopping - extract result before disposal
{
Result = _colorPicker.SelectedColor;
// Optionally cancel stop (e.g., prompt to save)
if (HasUnsavedChanges ())
{
return true; // Cancel stop
}
}
return base.OnIsRunningChanging (oldIsRunning, newIsRunning);
}
Lifecycle Properties
IsRunning- True when on theRunnableSessionStackIsModal- True when at the top of the stack (receiving all input)Result- The typed result value (set before stopping)
Lifecycle Events (CWP-Compliant)
IsRunningChanging- Cancellable event before added/removed from stackIsRunningChanged- Non-cancellable event after stack changeIsModalChanged- Non-cancellable event after modal state change
Modal Views (Legacy)
Views can run modally (exclusively capturing all input until closed). See Runnable for the legacy pattern.
Note: New code should use IRunnable<TResult> pattern (see above) for better type safety and lifecycle management.
Running a View Modally (Legacy)
Dialog dialog = new ()
{
Title = "Confirmation",
Width = Dim.Percent (50),
Height = Dim.Percent (50)
};
// Add content...
Label label = new () { Text = "Are you sure?", X = Pos.Center (), Y = 1 };
dialog.Add (label);
// Run modally - blocks until closed
Application.Run (dialog);
// Dialog has been closed
dialog.Dispose ();
Modal View Types
- Runnable - Base class for modal views, can fill entire screen
- Window - Overlapped container with border and title
- Dialog - Modal Window, centered with button support
- Wizard - Multi-step modal dialog
Wizard Example
Wizards let users step through multiple pages:
Wizard wizard = new () { Title = "Setup Wizard" };
WizardStep step1 = new () { Title = "Welcome" };
step1.Add (new Label { Text = "Welcome to the wizard!", X = 1, Y = 1 });
WizardStep step2 = new () { Title = "Configuration" };
step2.Add (new TextField { X = 1, Y = 1, Width = 30 });
wizard.AddStep (step1);
wizard.AddStep (step2);
Application.Run (wizard);
Advanced Topics
View Diagnostics
View.Diagnostics - ViewDiagnosticFlags for debugging:
Ruler- Shows a ruler around the ViewDrawIndicator- Shows an animated indicator when drawingFramePadding- Highlights the Frame with color
View States
Enabled- Whether the View is enabledVisible- Whether the View is visible- CanFocus - Whether the View can receive focus
- HasFocus - Whether the View currently has focus
Shadow Effects
ShadowStyle - ShadowStyle for drop shadows:
view.ShadowStyle = ShadowStyle.Transparent;
See Also
- Application Deep Dive - Instance-based application architecture
- Views Overview - Complete list of all built-in Views
- Layout Deep Dive - Detailed layout system documentation
- Drawing Deep Dive - Drawing system and color management
- Keyboard Deep Dive - Keyboard input handling
- Mouse Deep Dive - Mouse input handling
- Navigation Deep Dive - Focus and navigation system
- Scrolling Deep Dive - Scrolling and viewport management
- Command Deep Dive - Command pattern and bindings
- Arrangement Deep Dive - Movable and resizable views
- Configuration Deep Dive - Configuration and persistence
- Scheme Deep Dive - Color theming