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
  • Code Example - Binding a TextBox's Text Property
  • Binding to a ViewModel Event

Was this helpful?

Edit on GitHub
Export as PDF
  1. Code
  2. MonoGame
  3. Gum Forms
  4. Controls
  5. FrameworkElement

SetBinding

Introduction

SetBinding establishes a relationship between a property on the binding context and a property on the calling FrameworkElement. SetBinding is used to keep two properties synced, usually resulting changes on one of the properties automatically updating the other property.

SetBinding requires the bound FrameworkElement having a valid BindingContext - which can be either directly set or indirectly inherited from its parent.

The following are common SetBinding Examples:

  • Binding a TextBox's Text property to a ViewModel's CharacterName property

  • Binding a Button's IsEnabled property to a ViewModel's HasEnoughMoney property

  • Binding a ListBox's Items property to a ViewModel's AvailableFastTravelDestinations property

  • Binding a custom made PlayerJoinItem to a ViewModel's JoinState property

SetBinding takes two parameters:

  1. uiProperty - the property on the FrameworkElement

  2. vmProperty - the property on the ViewModel

Usually this method is called using the nameof keyword to avoid errors from typos and refactoring.

SetBinding exists on both FrameworkElement (Forms objects) as well as BindableGue (Gum runtime objects). This document is written in context of Forms controls, but binding can be performed directly on a runtime object's properties, including a FrameworkElement's Visual instance.

Code Example - Binding a TextBox's Text Property

The following code shows how to bind a TextBox's Text property to a ViewModel's CharacterName property:

// Assuming the TextBox's BindingContext is of type PlayerViewModel, and
// also assuming PlayerViewModel has a PlayerName property:
TextBoxInstance.SetBinding(
    nameof(TextBoxInstance.Text),
    nameof(PlayerViewModel.PlayerName));

Binding to a ViewModel Event

Binding can be performed on ViewModel events. When a bound event is raised, the FrameworkElement's bound handler is raised. Binding to an event is similar to explicitly adding an event handler, but the SetBinding method enables binding to events without having a ViewModel instance.

For example, consider a ViewModel which contains an event called EnemySpawned, which would be an event raised whenever a new enemy is spawned in a game.

public class GameViewModel : ViewModel
{
    // Regular ViewModel events can be used in SetBinding
    public event Action EnemySpawned;
    
    // If the event needs to be raised externally (outside of the ViewModel)
    // then a method for raising the event is needed:
    public void RaiseEnemySpawned() => EnemySpawned?.Invoke();
}

FrameworkElements can subscribe to this event using the normal event subscribing syntax in C#, but doing so requires access to the ViewModel.

var gameViewModel = this.BindingContext as GameViewModel;
if(gameViewModel != null)
{
    gameViewModel.EnemySpawned += HandleEnemySpawned;
}
// later, HandleEnemySpawned is declared:
void HandleEnemySpawned()
{
    // Perform logic related to enemy spawning
}

The code above is not as straight-forward as it might seem. BindingContext must be a valid GameViewModel, which means the code should be written in a place where the BindingContext is guaranteed to be set, such as overwriting the FrameworkElement's HandleVisualBindingContextChanged method. Furthermore, to prevent memory leaks a FrameworkElement should properly unsubscribe from its ViewModel events whenever its ViewModel changes.

We can simplify this code by letting the FrameworkElement handle this complexity by using SetBinding. The following code shows how this might look:

void CustomInitialize()
{
    SetBinding(
        nameof(HandleEnemySpawned),
        nameof(GameViewModel.EnemySpawned));
}

void HandleEnemySpawned()
{
    // Perform logic related to enemy spawning
}

The code above uses the same syntax as binding properties, but in this case we are binding an event to a method on our framework element.

PreviousModalRoot and PopupRootNextListBox

Last updated 2 months ago

Was this helpful?