Class MonoGameControl
Avalonia control that hosts a MonoGame rendering surface via OpenGL.
Inherits Avalonia.OpenGL.Controls.OpenGlControlBase so Avalonia manages the GL context lifecycle;
each compositor frame triggers OnOpenGlRender(GlInterface, int) which calls game.Tick().
public class MonoGameControl : OpenGlControlBase, INotifyPropertyChanged, IDataContextProvider, ILogical, IThemeVariantHost, IResourceHost, IResourceNode, IStyleHost, ISetLogicalParent, ISetInheritanceParent, ISupportInitialize, IStyleable, INamed, IInputElement, IDataTemplateHost, ISetterValue, ICustomHitTest
- Inheritance
-
AvaloniaObjectAnimatableStyledElementVisualLayoutableInteractiveInputElementControlOpenGlControlBaseMonoGameControl
- Implements
-
IDataContextProviderILogicalIThemeVariantHostIResourceHostIResourceNodeIStyleHostISetLogicalParentISetInheritanceParentIStyleableINamedIInputElementIDataTemplateHostISetterValueICustomHitTest
- Inherited Members
-
OpenGlControlBase.OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs)OpenGlControlBase.OnAttachedToVisualTree(VisualTreeAttachmentEventArgs)OpenGlControlBase.RequestNextFrameRendering()OpenGlControlBase.OnOpenGlLost()OpenGlControlBase.GlVersionControl.FocusAdornerPropertyControl.TagPropertyControl.ContextMenuPropertyControl.ContextFlyoutPropertyControl.RequestBringIntoViewEventControl.ContextRequestedEventControl.LoadedEventControl.UnloadedEventControl.SizeChangedEventControl.GetTemplateFocusTarget()Control.OnLoaded(RoutedEventArgs)Control.OnUnloaded(RoutedEventArgs)Control.OnSizeChanged(SizeChangedEventArgs)Control.OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs)Control.OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs)Control.OnGotFocus(GotFocusEventArgs)Control.OnCreateAutomationPeer()Control.FocusAdornerControl.DataTemplatesControl.ContextMenuControl.ContextFlyoutControl.IsLoadedControl.TagControl.ContextRequestedControl.LoadedControl.UnloadedControl.SizeChangedInputElement.FocusablePropertyInputElement.IsEnabledPropertyInputElement.IsEffectivelyEnabledPropertyInputElement.CursorPropertyInputElement.IsKeyboardFocusWithinPropertyInputElement.IsFocusedPropertyInputElement.IsHitTestVisiblePropertyInputElement.IsPointerOverPropertyInputElement.IsTabStopPropertyInputElement.GotFocusEventInputElement.LostFocusEventInputElement.KeyDownEventInputElement.KeyUpEventInputElement.TabIndexPropertyInputElement.TextInputEventInputElement.TextInputMethodClientRequestedEventInputElement.PointerEnteredEventInputElement.PointerExitedEventInputElement.PointerMovedEventInputElement.PointerPressedEventInputElement.PointerReleasedEventInputElement.PointerCaptureLostEventInputElement.PointerWheelChangedEventInputElement.TappedEventInputElement.HoldingEventInputElement.DoubleTappedEventInputElement.Focus(NavigationMethod, KeyModifiers)InputElement.OnAccessKey(RoutedEventArgs)InputElement.OnTextInput(TextInputEventArgs)InputElement.OnPointerEntered(PointerEventArgs)InputElement.OnPointerExited(PointerEventArgs)InputElement.OnPointerCaptureLost(PointerCaptureLostEventArgs)InputElement.UpdateIsEffectivelyEnabled()InputElement.FocusableInputElement.IsEnabledInputElement.CursorInputElement.IsKeyboardFocusWithinInputElement.IsFocusedInputElement.IsHitTestVisibleInputElement.IsPointerOverInputElement.IsTabStopInputElement.IsEffectivelyEnabledInputElement.TabIndexInputElement.KeyBindingsInputElement.IsEnabledCoreInputElement.GestureRecognizersInputElement.GotFocusInputElement.LostFocusInputElement.KeyDownInputElement.KeyUpInputElement.TextInputInputElement.TextInputMethodClientRequestedInputElement.PointerEnteredInputElement.PointerExitedInputElement.PointerMovedInputElement.PointerPressedInputElement.PointerReleasedInputElement.PointerCaptureLostInputElement.PointerWheelChangedInputElement.TappedInputElement.HoldingInputElement.DoubleTappedInteractive.RaiseEvent(RoutedEventArgs)Interactive.BuildEventRoute(RoutedEvent)Layoutable.DesiredSizePropertyLayoutable.WidthPropertyLayoutable.HeightPropertyLayoutable.MinWidthPropertyLayoutable.MaxWidthPropertyLayoutable.MinHeightPropertyLayoutable.MaxHeightPropertyLayoutable.MarginPropertyLayoutable.HorizontalAlignmentPropertyLayoutable.VerticalAlignmentPropertyLayoutable.UseLayoutRoundingPropertyLayoutable.UpdateLayout()Layoutable.ApplyTemplate()Layoutable.Measure(Size)Layoutable.Arrange(Rect)Layoutable.InvalidateMeasure()Layoutable.InvalidateArrange()Layoutable.AffectsMeasure<T>(params AvaloniaProperty[])Layoutable.AffectsArrange<T>(params AvaloniaProperty[])Layoutable.MeasureCore(Size)Layoutable.MeasureOverride(Size)Layoutable.ArrangeCore(Rect)Layoutable.ArrangeOverride(Size)Layoutable.OnMeasureInvalidated()Layoutable.OnVisualParentChanged(Visual, Visual)Layoutable.WidthLayoutable.HeightLayoutable.MinWidthLayoutable.MaxWidthLayoutable.MinHeightLayoutable.MaxHeightLayoutable.MarginLayoutable.HorizontalAlignmentLayoutable.VerticalAlignmentLayoutable.DesiredSizeLayoutable.IsMeasureValidLayoutable.IsArrangeValidLayoutable.UseLayoutRoundingLayoutable.EffectiveViewportChangedLayoutable.LayoutUpdatedVisual.BoundsPropertyVisual.ClipToBoundsPropertyVisual.ClipPropertyVisual.IsVisiblePropertyVisual.OpacityPropertyVisual.OpacityMaskPropertyVisual.EffectPropertyVisual.HasMirrorTransformPropertyVisual.RenderTransformPropertyVisual.RenderTransformOriginPropertyVisual.FlowDirectionPropertyVisual.VisualParentPropertyVisual.ZIndexPropertyVisual.GetFlowDirection(Visual)Visual.SetFlowDirection(Visual, FlowDirection)Visual.InvalidateVisual()Visual.Render(DrawingContext)Visual.AffectsRender<T>(params AvaloniaProperty[])Visual.InvalidateMirrorTransform()Visual.BoundsVisual.ClipToBoundsVisual.ClipVisual.IsEffectivelyVisibleVisual.IsVisibleVisual.OpacityVisual.OpacityMaskVisual.EffectVisual.HasMirrorTransformVisual.RenderTransformVisual.RenderTransformOriginVisual.FlowDirectionVisual.ZIndexVisual.VisualChildrenVisual.VisualRootVisual.BypassFlowDirectionPoliciesVisual.AttachedToVisualTreeVisual.DetachedFromVisualTreeStyledElement.DataContextPropertyStyledElement.NamePropertyStyledElement.ParentPropertyStyledElement.TemplatedParentPropertyStyledElement.ThemePropertyStyledElement.BeginInit()StyledElement.EndInit()StyledElement.ApplyStyling()StyledElement.InitializeIfNeeded()StyledElement.OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs)StyledElement.OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs)StyledElement.OnDataContextBeginUpdate()StyledElement.OnDataContextEndUpdate()StyledElement.OnInitialized()StyledElement.NameStyledElement.ClassesStyledElement.DataContextStyledElement.IsInitializedStyledElement.StylesStyledElement.StyleKeyStyledElement.ResourcesStyledElement.TemplatedParentStyledElement.ThemeStyledElement.LogicalChildrenStyledElement.PseudoClassesStyledElement.StyleKeyOverrideStyledElement.ParentStyledElement.ActualThemeVariantStyledElement.AttachedToLogicalTreeStyledElement.DetachedFromLogicalTreeStyledElement.DataContextChangedStyledElement.InitializedStyledElement.ResourcesChangedStyledElement.ActualThemeVariantChangedAnimatable.TransitionsPropertyAnimatable.OnPropertyChangedCore(AvaloniaPropertyChangedEventArgs)Animatable.TransitionsAvaloniaObject.CheckAccess()AvaloniaObject.VerifyAccess()AvaloniaObject.ClearValue(AvaloniaProperty)AvaloniaObject.ClearValue<T>(AvaloniaProperty<T>)AvaloniaObject.ClearValue<T>(StyledProperty<T>)AvaloniaObject.ClearValue<T>(DirectPropertyBase<T>)AvaloniaObject.GetHashCode()AvaloniaObject.GetValue(AvaloniaProperty)AvaloniaObject.GetValue<T>(StyledProperty<T>)AvaloniaObject.GetValue<T>(DirectPropertyBase<T>)AvaloniaObject.GetBaseValue<T>(StyledProperty<T>)AvaloniaObject.IsAnimating(AvaloniaProperty)AvaloniaObject.IsSet(AvaloniaProperty)AvaloniaObject.SetValue<T>(StyledProperty<T>, T, BindingPriority)AvaloniaObject.SetValue<T>(DirectPropertyBase<T>, T)AvaloniaObject.SetCurrentValue<T>(StyledProperty<T>, T)AvaloniaObject.Bind(AvaloniaProperty, IBinding)AvaloniaObject.CoerceValue(AvaloniaProperty)AvaloniaObject.RaisePropertyChanged<T>(DirectPropertyBase<T>, T, T)AvaloniaObject.SetAndRaise<T>(DirectPropertyBase<T>, ref T, T)AvaloniaObject.InheritanceParentAvaloniaObject.this[AvaloniaProperty]AvaloniaObject.this[IndexerDescriptor]AvaloniaObject.PropertyChanged
Remarks
Assign your Game instance via the Game property or
SetGame(Game). Do not call game.Run() yourself — the control
calls it on the first render frame so that LoadContent() executes with an active
GL context. The control also forces IsFixedTimeStep = false and
SynchronizeWithVerticalRetrace = false to prevent MonoGame's internal governor
from fighting Avalonia's compositor callback.
XAML usage:
// doctest-ignore
// <controls:MonoGameControl x:Name="GameView" />
Code-behind:
// doctest-ignore
GameView.SetGame(new MyGame());
Constructors
MonoGameControl()
Initializes a new instance of MonoGameControl and marks it focusable so that keyboard events are delivered after the first pointer click.
public MonoGameControl()
Fields
GameProperty
AvaloniaProperty backing the Game property.
Supports XAML attribute assignment and {Binding} expressions, enabling
MVVM patterns where a ViewModel exposes the game instance.
public static readonly StyledProperty<Game?> GameProperty
Field Value
- StyledProperty<Game>
Properties
Game
The Game instance hosted by this control. Settable via XAML binding or code-behind. Equivalent to calling SetGame(Game).
public Game? Game { get; set; }
Property Value
Methods
OnKeyDown(KeyEventArgs)
Invoked when an unhandled Avalonia.Input.InputElement.KeyDownEvent reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
protected override void OnKeyDown(KeyEventArgs e)
Parameters
eKeyEventArgsData about the event.
OnKeyUp(KeyEventArgs)
Invoked when an unhandled Avalonia.Input.InputElement.KeyUpEvent reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
protected override void OnKeyUp(KeyEventArgs e)
Parameters
eKeyEventArgsData about the event.
OnLostFocus(RoutedEventArgs)
Called before the Avalonia.Input.InputElement.LostFocus event occurs.
protected override void OnLostFocus(RoutedEventArgs e)
Parameters
eRoutedEventArgsThe event args.
OnOpenGlDeinit(GlInterface)
Called by Avalonia when the OpenGL context is destroyed (control removed, window closed).
Deactivates the MonoGame platform so game.Tick() is skipped on any stray callbacks,
disposes GPU resources, and resets all GL-related fields so that a subsequent re-attach
(e.g. the user reopens a docked tab) restarts cleanly from OnOpenGlInit(GlInterface).
protected override void OnOpenGlDeinit(GlInterface gl)
Parameters
glGlInterface
OnOpenGlInit(GlInterface)
Called once by Avalonia when the OpenGL context is created for this control.
Stores the Avalonia.OpenGL.GlInterface and marks the MonoGame platform as active,
which allows game.Tick() to proceed. Game start (LoadContent) is
intentionally deferred to the first OnOpenGlRender(GlInterface, int) call so that
GPU resource creation happens with a guaranteed current GL context.
protected override void OnOpenGlInit(GlInterface gl)
Parameters
glGlInterface
OnOpenGlRender(GlInterface, int)
Called every compositor frame by Avalonia to produce the next rendered image.
This is the main MonoGame integration point — it calls game.Tick() which
invokes Update() and Draw(), then dispatches each registered
SubViewGameControl draw delegate.
protected override void OnOpenGlRender(GlInterface gl, int fb)
Parameters
glGlInterfacefbint
Remarks
On the first invocation this method performs one-time deferred initialization:
- Loads MonoGame.OpenGL entry points (requires an active GL context)
- Calls
game.Run()soLoadContent()runs with a live context - Forces
IsFixedTimeStep = falseandSynchronizeWithVerticalRetrace = falseto prevent MonoGame's internal timing governor from interfering with Avalonia's compositor-driven callback rate
OnPointerMoved(PointerEventArgs)
Invoked when an unhandled Avalonia.Input.InputElement.PointerMovedEvent reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
protected override void OnPointerMoved(PointerEventArgs e)
Parameters
ePointerEventArgsData about the event.
OnPointerPressed(PointerPressedEventArgs)
Invoked when an unhandled Avalonia.Input.InputElement.PointerPressedEvent reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
protected override void OnPointerPressed(PointerPressedEventArgs e)
Parameters
ePointerPressedEventArgsData about the event.
OnPointerReleased(PointerReleasedEventArgs)
Invoked when an unhandled Avalonia.Input.InputElement.PointerReleasedEvent reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
protected override void OnPointerReleased(PointerReleasedEventArgs e)
Parameters
ePointerReleasedEventArgsData about the event.
OnPointerWheelChanged(PointerWheelEventArgs)
Invoked when an unhandled Avalonia.Input.InputElement.PointerWheelChangedEvent reaches an element in its route that is derived from this class. Implement this method to add class handling for this event.
protected override void OnPointerWheelChanged(PointerWheelEventArgs e)
Parameters
ePointerWheelEventArgsData about the event.
OnPropertyChanged(AvaloniaPropertyChangedEventArgs)
Called when a avalonia property changes on the object.
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
Parameters
changeAvaloniaPropertyChangedEventArgsThe property change details.
Remarks
Reacts to GameProperty changes by wiring the new game's window bounds
provider and Avalonia window provider, and to BoundsProperty changes by
propagating new dimensions to MonoGame's backbuffer.
Avalonia styled properties do not have per-property virtual callbacks; overriding
OnPropertyChanged is the idiomatic Avalonia way to respond to any styled
property change from within a control subclass.
SetGame(Game)
Binds a Game to this control. Equivalent to setting the
Game property. Do not call game.Run() separately —
OnOpenGlRender(GlInterface, int) calls game.Run() automatically on the first
frame so that LoadContent() executes with an active GL context.
Before calling game.Run(), the control sets game.IsFixedTimeStep = false
and GraphicsDeviceManager.SynchronizeWithVerticalRetrace = false automatically.
Both flags are required for correct behaviour in Avalonia — MonoGame's internal governor
and VSync wait fight Avalonia's render callback. You do not need to set them yourself.
public void SetGame(Game game)
Parameters
gameGame