LogoLogo
  • Gum Tool
    • Introduction
    • Setup
      • Running from Source
    • Showcase
    • Tutorials and Examples
      • Intro Tutorials
        • 1 - The Basics
        • 2 - Variables Tab
        • 3 - Files
        • 4 - Components
        • 5 - Exposing Variables
        • 6 - Parent
        • 7 - States
        • 8 - State Categories
      • Animation Tutorials
        • 1 - Introduction to Animation
        • 2 - Creating an Animation
        • 3 - Playing Animations inside other Animations
        • 4 - Combining Multiple Categories
      • Examples
        • Bottom-Up Stack
        • Centering
        • Custom NineSlice
        • Health Bar
        • Padding
    • Gum Elements
      • General Properties
        • Alpha
        • Base Type (Inheritance)
        • Blend
        • Clips Children
        • Has Events
        • Height Units
        • Ignored By Parent Size
        • Locked
        • Max Height
        • Max Width
        • Min Height
        • Min Width
        • Order
        • Parent
        • Rotation
        • Visible
        • Variable References
        • Width Units
        • X
        • X Origin
        • X Units
        • Y
        • Y Origin
        • Y Units
      • Behaviors
        • Default Implementation
      • Circle
      • ColoredRectangle
      • Component
        • Default Child Container
      • Container
        • Children Layout
        • Contained Type
        • Is Render Target
        • Stack Spacing
        • Wraps Children
      • NineSlice
        • Blend
        • Custom Frame Texture Coordinate Width
        • Texture Address
        • Texture Left
        • Texture Top
      • Polygon
        • Points
      • Skia Standard Elements
        • General Properties
          • Has Dropshadow
          • Is Filled
          • Use Gradient
        • Arc
          • Start Angle
          • Sweep Angle
          • Thickness
        • Canvas
        • ColoredCircle
        • LottieAnimation
        • RoundedRectangle
          • Corner Radius
        • Svg
      • Sprite
        • Color
        • Source File
        • Texture Address
        • Wrap
      • States
        • Categories
      • Text
        • Blue
        • Color
        • Font
        • Font Scale
        • Font Size
        • Green
        • Is Bold
        • Is Italic
        • MaxLettersToShow
        • Outline Thickness
        • Red
        • Text
        • Text Overflow Horizontal Mode
        • Text Overflow Vertical Mode
        • Use Custom Font
        • Use Font Smoothing
    • Project Tab
    • Code Tab
      • Runtime Generation Details
      • Generation Scope
      • Inheritance Location
      • Is CodeGen Plugin Enabled
      • Show CodeGen Preview
    • Localization
    • Menu
      • Content
      • Project Properties
    • Plugins
      • AddAndRemoveVariablesForType
      • AddMenuItem
      • Export
      • Setting Up Post Build Events
    • Variables
      • Add Variable
    • Bitmap font generator (.fnt)
    • Upgrading
      • Migrating 2025 April 27 to Preview
      • Breaking Changes
        • Removal of Variable Spaces
  • Code
    • Gum Code Reference
      • AnimationRuntime
      • BitmapCharacterInfo
      • BitmapFont
      • Camera
      • CircleRuntime
      • ColoredRectangleRuntime
      • Component Runtimes
      • ContainerRuntime
      • Cursor
      • Gum Class Overview
      • DataUiGrid
        • Reflection
        • Categories
      • ElementSave
        • ToGraphicalUiElement
      • GraphicalUiElement
        • Absolute Values
        • AddToManagers
        • AnimateSelf
        • ApplyState
        • BlendState
        • CanvasHeight
        • CanvasWidth
        • Children
        • ContainedElements
        • Font Values
        • GetAbsoluteHeight
        • GetAbsoluteWidth
        • GetChildByNameRecursively
        • GetFrameworkElementByName
        • IsAllLayoutSuspended
        • Parent
        • RemoveFromManagers
        • UpdateLayout
      • GumProjectSave
      • IDataUi
      • InstanceMember
      • InstanceSave
      • InteractiveGue
        • CurrentInputReceiver
        • RaiseChildrenEventsOutsideOfBounds
        • RollOverBubbling
      • IPositionedSizedObject
      • Layer
      • NineSliceRuntime
      • RectangleRuntime
      • Renderer
        • SinglePixelTexture
      • SelectedState
      • SpriteRenderer
        • LastFrameDrawStates
      • SpriteRuntime
        • TextureAddress
        • TextureHeight
        • TextureLeft
        • TextureTop
        • TextureWidth
      • TextRuntime
        • Color
        • FontScale
        • FontSize
        • HorizontalAlignment
        • Text Wrapping
        • VerticalAlignment
      • VariableSave
    • FNA
    • Kni
    • Meadow
    • MonoGame
      • Setup
        • Linking Game Project to Source (Optional)
      • Tutorials
        • Gum Project Forms Tutorial
          • Setup
          • Gum Screens
          • Common Component Types
          • Styling
          • Multiple Screens
        • Code-Only Gum Forms Tutorial
          • Setup
          • Forms Controls
          • ListBox Items
          • Input in Forms
        • [Deprecated] Gum Project (.gumx) Tutorial
          • Setup
          • Gum Screens
          • Gum Forms
          • Customizing Forms
          • Strongly Typed Components Using Code Generation
          • Multiple Screens
      • Setup for GumBatch (Optional)
      • Loading a Gum Project (Optional)
      • async Programming
      • Custom Runtimes
      • GumBatch
      • Gum Forms
        • Binding (ViewModels)
        • Controls
          • Button
          • CheckBox
          • FrameworkElement
            • BindingContext
            • IsEnabled
            • IsFocused
            • ModalRoot and PopupRoot
            • SetBinding
          • ListBox
          • ListBoxItem
          • MenuItem
          • PasswordBox
          • RadioButton
          • ScrollViewer
            • VerticalScrollBarValue
          • StackPanel
          • Slider
          • TextBox
        • Control Customization In Code
          • MenuItem
        • Control Customization in Gum Tool
        • Gamepad Support
        • Keyboard Support
        • Troubleshooting
      • File Loading
      • Resizing the Game Window
      • Known Issues
      • Samples
        • MonoGameGumFormsSample
    • Nez
    • Silk.NET
    • SkiaGum
      • Setup
        • WPF
    • .NET MAUI
      • Setup
Powered by GitBook
On this page
  • Introduction
  • Common Control Properties
  • Forms Control vs Visual
  • Code Organization
  • Label
  • Button
  • CheckBox
  • ComboBox
  • ListBox
  • RadioButton
  • ScrollViewer
  • Slider
  • TextBox

Was this helpful?

Edit on GitHub
Export as PDF
  1. Code
  2. MonoGame
  3. Tutorials
  4. Code-Only Gum Forms Tutorial

Forms Controls

Introduction

Forms controls are a collection of classes which provide common UI behavior. You will probably be familiar with many controls. The most common controls include:

  • Button

  • CheckBox

  • ComboBox

  • Image

  • Label

  • ListBox

  • RadioButton

  • ScrollViewer

  • Slider

  • TextBox

All controls are in the MonoGameGum.Forms.Controls namespace.

Forms naming is based on naming from WPF. If you are familiar with WPF or similar libraries like Avalonia, you may find many of the names and concepts familiar.

Common Control Properties

All controls share a few common properties and characteristics. The following list provides a high-level introduction to forms control similarities. If the list doesn't make sense don't worry, we'll cover each topic in this and following tutorials.

  • All controls can be added to a StackPanel. Technically, any control can be added to any other control, but for this tutorial we'll keep things simple by adding only to a StackPanel.

  • All controls have a Visual property which can be used to position, size, and perform advance layout behavior. This Visual property is ultimately a GraphicalUiElement which provides access to all Gum layout properties.

  • All controls can receive input from the mouse (usually through the Gum Cursor object). Most controls can also receive focus and input from gamepads.

  • All controls support binding by assigning their BindingContext property. Children controls inherit BindingContext from their parents if the BindingContext is not explicitly assigned.

For the rest of this tutorial we'll add a few of the most common controls to our project and show how to work with them. Note that for this tutorial I've removed the Button control from the previous tutorial.

We also assume that your project has a mainPanel to hold all controls.

Forms Control vs Visual

As we'll see below, each forms control has a specific purpose. Buttons are clicked, Labels display read-only strings, and TextBoxes can be used to input text. Each control provides properties and events specific to its purpose, standardizing the way each works.

However, each control also wraps a Visual object which gives you full layout control. The Visual property is of type GraphicalUiElement, and it has access to the full Gum layout engine. For example, a button could be made to be as wide as its parents using the following code:

// assuming MyButton is a valid Button:
MyButton.Visual.Width = 0;
MyButton.Visual.WidthUnits = DimensionUnitType.RelativeToContainer;

Code Organization

For the sake of brevity, we will add all of our controls to the Root object, and all code will be added to the game's Initialize method after the Root has been created. Of course a full game may require more advanced organization but we'll keep everything in the Game Initialize for simplicity.

Label

Labels are text objects which can display a string. Labels do not have any direct interaction such as responding to clicks. The following code adds a label to the project:

var label = new Label();
mainPanel.AddChild(label);
label.Text = $"I was created at {System.DateTime.Now}";

The rest of this tutorial assumes that the Label is not removed. It is used to show when events have occurred.

Button

Button controls are usually added when a user needs to perform a command. Buttons can be clicked with the mouse and gamepad, and their click event can be manually invoked for custom support such as pressing Enter on the keyboard.

The following code creates two buttons. One is disabled so it does not respond to click events:

var button = new Button();
mainPanel.AddChild(button);
button.Text = "Click Me";
button.Click += (_, _) => 
    label.Text = $"Button clicked @ {System.DateTime.Now}";

var disabledButton = new Button();
mainPanel.AddChild(disabledButton);
disabledButton.Text = "Disabled Button";
disabledButton.IsEnabled = false;
disabledButton.Click += (_, _) =>
    label.Text = "This never happens";

Notice that the Label and two Buttons are stacked top-to-bottom. This is the default behavior layout behavior of StackPanels.

As mentioned earlier, layout-related properties can be accessed through a control's Visual property.

CheckBox

CheckBox controls allow the user to toggle a bool value by clicking on it. Just like Button, the CheckBoxes support clicking with mouse and gamepad and changing the IsChecked property in code.

The following code creates a CheckBox with two method handlers (Checked/Unchecked):

var checkBox = new CheckBox();
mainPanel.AddChild(checkBox);
checkBox.Text = "Click Me";
checkBox.Checked += (_, _) => label.Text = "CheckBox checked";
checkBox.Unchecked += (_, _) => label.Text = "CheckBox unchecked";

ComboBox

ComboBox provides a collapsible way to display and select from a list of options.

The following code creates a ComboBox which raises an event whenever an item is selected.

var comboBox = new ComboBox();
for (int i = 0; i < 20; i++)
{
    comboBox.Items.Add($"Item {i}");
}
comboBox.SelectionChanged += (_, _) =>
{
    label.Text = "Selected: " + comboBox.SelectedObject;
};
mainPanel.AddChild(comboBox);

ListBox

ListBox provides a way to display a list of items. Each item can be selected.

The following code creates a ListBox which raises an event whenever an item is selected.

var listBox = new ListBox();
listBox.Visual.Width = 150;
listBox.Visual.Height = 300;

for (int i = 0; i < 20; i++)
{
    listBox.Items.Add($"Item {i}");
}
listBox.SelectionChanged += (_, _) =>
{
    label.Text = 
        $"Selected item is {listBox.SelectedObject} at index {listBox.SelectedIndex}";
};
mainPanel.AddChild(listBox);

RadioButton

RadioButton controls allow the user to view a set of options and pick from one of the available options. Radio buttons are mutually exclusive within their group. Radio buttons can be grouped together by putting them in common containers, such as StackLayouts.

The following creates six radio buttons in two separate groups.

var group1 = new StackPanel();
mainPanel.AddChild(group1);

var group2 = new StackPanel();
// move group 2 down slightly:
group2.Y = 10;
mainPanel.AddChild(group2);

var radioButtonA = new RadioButton();
radioButtonA.Text = "Option A";
group1.AddChild(radioButtonA);

var radioButtonB = new RadioButton();
radioButtonB.Text = "Option B";
group1.AddChild(radioButtonB);

var radioButtonC = new RadioButton();
radioButtonC.Text = "Option C";
group1.AddChild(radioButtonC);


var radioButton1 = new RadioButton();
radioButton1.Text = "Option 1";
group2.AddChild(radioButton1);

var radioButton2 = new RadioButton();
radioButton2.Text = "Option 2";
group2.AddChild(radioButton2);

var radioButton3 = new RadioButton();
radioButton3.Text = "Option 3";
group2.AddChild(radioButton3);

ScrollViewer

ScrollViewer provides a scrollable panel for controls. ScrollViewers are similar in concept to ListBoxes, but they can contain any type of item rather than only ListBoxItems.

The following code creates a ScrollViewer and adds buttons using AddChild.

var scrollViewer = new ScrollViewer();
scrollViewer.Width = 200;
mainPanel.AddChild(scrollViewer);

for(int i = 0; i < 15; i++)
{
    var button = new Button();
    button.Text = "Button " + i;
    scrollViewer.AddChild(button);
}

Slider

Slider controls allow the user to select a value between a minimum and maximum value.

The following code creates a Slider which raises an event whenever its Value changes.

var slider = new Slider();
slider.Width = 200;
slider.Minimum = 0;
slider.Maximum = 100;
slider.ValueChanged += (_,_) => 
    label.Text = $"Slider value: {slider.Value}";
mainPanel.AddChild(slider);

TextBox

TextBox controls allow the user to see and edit string values. TextBoxes support typing with the keyboard, copy/paste, selection, and multiple lines of text.

TextBoxes are automatically focused when clicked, but IsFocused can be explicitly set to give focus.

The following code creates a TextBox which raises an event whenever its text is changed. The text is then copied over to a label.

var textBox = new TextBox();
textBox.Placeholder = "Enter text here...";
textBox.TextChanged += (_, _) => 
    label.Text = $"Text box text is now: {textBox.Text}";
mainPanel.AddChild(textBox);
PreviousSetupNextListBox Items

Last updated 1 month ago

Was this helpful?

For more information about all of the properties available to GraphicalUiElement, see the section of the Gum tool - all properties in the tool are also available in code.

These tutorials focus on the Forms controls themselves but for more information you can look at the different properties available in the pages.

General Properties
General Properties
Label displaying when it was created
Buttons only respond to Click if IsEnabled is set to true (default)
CheckBox responds to clicks
ComboBox responding to items being selected
ListBox responding to items being selected
RadioButtons responding to clicks in two different groups
ScrollViewer containing buttons
Slider responding to cursor input
TextBox responding to text input