In This Article

CanvasControl Class

Represents a control that supports custom rendering of content.

public class CanvasControl : Control, IDataContextProvider, ILogical, IThemeVariantHost, IResourceHost, IResourceNode, IStyleHost, ISetLogicalParent, ISetInheritanceParent, INamed, IInputElement, IDataTemplateHost, ISetterValue
Inheritance:
object AvaloniaObject Animatable StyledElement Visual Layoutable Interactive InputElement Control object
Derived:
AnimatedTextPresenter
Implements:
IDataContextProvider ILogical IThemeVariantHost IResourceHost IResourceNode IStyleHost ISetLogicalParent ISetInheritanceParent INamed IInputElement IDataTemplateHost ISetterValue

Constructors

CanvasControl()

Initializes an instance of the class.

public CanvasControl()

Properties

IsAnimationEnabled

Indicates whether animations are enabled for the control.

public bool IsAnimationEnabled { get; set; }

Property Value

bool:

The default value is true.

Methods

CreateDrawContext(DrawingContext, Rect)

Creates a CanvasDrawContext for the current render pass.

protected virtual CanvasDrawContext CreateDrawContext(DrawingContext drawingContext, Rect bounds)
Parameter Type Description
drawingContext DrawingContext

The native object used for drawing.

bounds Rect

The bounds in which to draw.

Returns

CanvasDrawContext:

The created CanvasDrawContext.

InvalidateRender()

Invalidates and repaints the control.

public void InvalidateRender()

MeasureCore(Size)

The default implementation of the control's measure pass.

protected override Size MeasureCore(Size availableSize)
Parameter Type Description
availableSize Size

The size available to the control.

Returns

Size:

The desired size for the control.

Remarks

This method calls Avalonia.Layout.Layoutable.MeasureOverride(Avalonia.Size) which is probably the method you want to override in order to modify a control's arrangement.

OnAttachedToVisualTree(VisualTreeAttachmentEventArgs)

Called when the control is added to a rooted visual tree.

protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
Parameter Type Description
e VisualTreeAttachmentEventArgs

The event args.

OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs)

Called when the control is removed from a rooted visual tree.

protected override void OnDetachedFromVisualTree(VisualTreeAttachmentEventArgs e)
Parameter Type Description
e VisualTreeAttachmentEventArgs

The event args.

OnDraw(CanvasDrawContext)

Draws the control's content.

protected virtual void OnDraw(CanvasDrawContext context)
Parameter Type Description
context CanvasDrawContext

The context to use for drawing.

Remarks

The Draw event is raised after this method returns.

OnEffectiveVisibilityChanged()

Called when a change in effective visibility is observed for rendering coordination.

protected virtual void OnEffectiveVisibilityChanged()

Remarks

The render coordinator is suspended or resumed before this method is invoked. Derived controls are responsible for canceling, completing, or rebasing animation state as appropriate. Effective visibility is checked before new rendering requests and active source frames. Platforms also observe ancestor visibility through layout or native visibility notifications. A custom host can call RefreshEffectiveVisibility() to report a change immediately.

OnIsAnimationEnabledChanged()

Called when the IsAnimationEnabled property value changes.

protected virtual void OnIsAnimationEnabledChanged()

Remarks

Derived controls are responsible for applying their animation policy and updating visual state as appropriate.

OnPropertyChanged(AvaloniaPropertyChangedEventArgs)

Called when a avalonia property changes on the object.

protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
Parameter Type Description
change AvaloniaPropertyChangedEventArgs

The property change details.

RefreshEffectiveVisibility()

Refreshes the effective visibility used for rendering coordination.

public void RefreshEffectiveVisibility()

Remarks

Call this method on the UI thread to synchronously observe the current effective visibility. This method does not change visibility. Custom hosts can call it after visibility changes.

When the observed value changes, rendering coordination is updated before OnEffectiveVisibilityChanged() is called synchronously. Repeated calls with the same effective visibility do not notify again. A detached control remains suspended.

Render(DrawingContext)

Renders the visual to a Avalonia.Media.DrawingContext.

public override sealed void Render(DrawingContext context)
Parameter Type Description
context DrawingContext

The drawing context.

RequestContinuousRendering(Action<TimeSpan>)

Registers a callback that updates state for continuous rendering.

protected IDisposable RequestContinuousRendering(Action<TimeSpan> updateCallback)
Parameter Type Description
updateCallback Action<TimeSpan>

The callback to invoke for each frame.

Returns

IDisposable:

An object that removes the callback registration when disposed.

Remarks

The callback receives a monotonic control-local timestamp that pauses while the control is hidden or detached. The first frame after the coordinator becomes active establishes the timestamp baseline. Dispose the returned token on the UI thread to stop this registration. A failing callback is removed; other due callbacks run before the original exception is rethrown. Disposing the last token resets the local timestamp for future registrations.

The callback registration is independent of IsAnimationEnabled. Derived controls are responsible for applying their animation policy and disposing the registration when work completes.

RequestContinuousRendering(Action<TimeSpan>, TimeSpan)

Registers a callback that updates state for continuous rendering at no more than the specified cadence.

protected IDisposable RequestContinuousRendering(Action<TimeSpan> updateCallback, TimeSpan minimumFrameInterval)
Parameter Type Description
updateCallback Action<TimeSpan>

The callback to invoke when a frame is due.

minimumFrameInterval TimeSpan

The minimum elapsed time between callbacks, or Zero to invoke for every source frame.

Returns

IDisposable:

An object that removes the callback registration when disposed.

Remarks

The callback receives the same monotonic control-local timestamp as an unconstrained registration. Source frames that arrive before the minimum interval elapses do not invoke the callback or invalidate the control unless another registration is due.

The minimum interval limits only this registration. It does not change the shared frame-source cadence, prevent another due registration from invalidating the control, or guarantee that callbacks achieve a particular frame rate.

The callback registration is independent of IsAnimationEnabled. Derived controls are responsible for applying their animation policy and disposing the registration when work completes.

Exceptions

Type Condition
ArgumentOutOfRangeException

minimumFrameInterval is negative.

StartAnimation(TimeSpan, Action<double>, Easing?, TimeSpan, Action?)

Starts a finite animation.

protected IDisposable StartAnimation(TimeSpan duration, Action<double> updateCallback, Easing? easing = null, TimeSpan delay = default, Action? completedCallback = null)
Parameter Type Description
duration TimeSpan

The nonnegative animation duration.

updateCallback Action<double>

The callback that receives eased progress for each frame.

easing Easing

The easing applied to raw progress, or null for linear progress.

delay TimeSpan

The nonnegative delay before progress begins.

completedCallback Action

The callback to invoke after the final progress update.

Returns

IDisposable:

An object that cancels the animation without invoking its completion callback when disposed on the UI thread.

Remarks

All active animations share one continuous-render registration. Updates run before completion callbacks, followed by one render invalidation. The final progress is exactly one; intermediate easing may overshoot. A zero duration still defers callbacks until an eligible frame after the delay.

The first eligible frame establishes an idle engine's timestamp baseline. Animations added to an active engine use its latest timestamp and first update on a subsequent frame. Hidden or detached controls pause elapsed time. Derived controls can cancel or complete their visual state in visibility or lifecycle hooks.

Call this method and dispose its token on the UI thread. Easing and callbacks run on that thread. A failing animation is removed; other animations continue before the original exception is rethrown. Surviving animations remain scheduled if the host handles the exception and continues dispatching.

This method is independent of IsAnimationEnabled. Derived controls are responsible for applying their animation policy and providing static output when animation is unavailable or inappropriate.

Exceptions

Type Condition
ArgumentNullException

updateCallback is null.

ArgumentOutOfRangeException

duration or delay is negative.

Events

Draw

Occurs when the canvas should be rendered.

public event EventHandler<CanvasDrawEventArgs>? Draw

Event Type

EventHandler<CanvasDrawEventArgs>

Fields

IsAnimationEnabledProperty

Defines the IsAnimationEnabled property.

public static readonly StyledProperty<bool> IsAnimationEnabledProperty

Inherited Members

  • Control.FocusAdornerProperty
  • Control.TagProperty
  • Control.ContextMenuProperty
  • Control.ContextFlyoutProperty
  • Control.RequestBringIntoViewEvent
  • Control.LoadedEvent
  • Control.UnloadedEvent
  • Control.SizeChangedEvent
  • Control.GetTemplateFocusTarget()
  • Control.OnLoaded(RoutedEventArgs)
  • Control.OnUnloaded(RoutedEventArgs)
  • Control.OnSizeChanged(SizeChangedEventArgs)
  • Control.OnAttachedToVisualTreeCore(VisualTreeAttachmentEventArgs)
  • Control.OnDetachedFromVisualTreeCore(VisualTreeAttachmentEventArgs)
  • Control.OnGotFocus(FocusChangedEventArgs)
  • Control.OnLostFocus(FocusChangedEventArgs)
  • Control.OnCreateAutomationPeer()
  • Control.OnPointerReleased(PointerReleasedEventArgs)
  • Control.OnKeyUp(KeyEventArgs)
  • Control.UpdateDataValidation(AvaloniaProperty, BindingValueType, Exception)
  • Control.FocusAdorner
  • Control.DataTemplates
  • Control.ContextMenu
  • Control.ContextFlyout
  • Control.IsLoaded
  • Control.Tag
  • Control.Loaded
  • Control.Unloaded
  • Control.SizeChanged
  • InputElement.FocusableProperty
  • InputElement.IsEnabledProperty
  • InputElement.IsEffectivelyEnabledProperty
  • InputElement.CursorProperty
  • InputElement.IsKeyboardFocusWithinProperty
  • InputElement.IsFocusedProperty
  • InputElement.IsHitTestVisibleProperty
  • InputElement.IsPointerOverProperty
  • InputElement.IsTabStopProperty
  • InputElement.GotFocusEvent
  • InputElement.GettingFocusEvent
  • InputElement.LostFocusEvent
  • InputElement.LosingFocusEvent
  • InputElement.KeyDownEvent
  • InputElement.KeyUpEvent
  • InputElement.TabIndexProperty
  • InputElement.TextInputEvent
  • InputElement.TextInputMethodClientRequestedEvent
  • InputElement.PointerEnteredEvent
  • InputElement.PointerExitedEvent
  • InputElement.PointerMovedEvent
  • InputElement.PointerPressedEvent
  • InputElement.PointerReleasedEvent
  • InputElement.PointerCaptureLostEvent
  • InputElement.PointerWheelChangedEvent
  • InputElement.ContextRequestedEvent
  • InputElement.ContextCanceledEvent
  • InputElement.IsHoldingEnabledProperty
  • InputElement.IsHoldWithMouseEnabledProperty
  • InputElement.PinchEvent
  • InputElement.PinchEndedEvent
  • InputElement.PullGestureEvent
  • InputElement.PullGestureEndedEvent
  • InputElement.SwipeGestureEvent
  • InputElement.SwipeGestureEndedEvent
  • InputElement.ScrollGestureEvent
  • InputElement.ScrollGestureInertiaStartingEvent
  • InputElement.ScrollGestureEndedEvent
  • InputElement.PointerTouchPadGestureMagnifyEvent
  • InputElement.PointerTouchPadGestureRotateEvent
  • InputElement.PointerTouchPadGestureSwipeEvent
  • InputElement.TappedEvent
  • InputElement.RightTappedEvent
  • InputElement.HoldingEvent
  • InputElement.DoubleTappedEvent
  • InputElement.Focus(NavigationMethod, KeyModifiers)
  • InputElement.OnAccessKey(RoutedEventArgs)
  • InputElement.OnGettingFocus(FocusChangingEventArgs)
  • InputElement.OnLosingFocus(FocusChangingEventArgs)
  • InputElement.OnKeyDown(KeyEventArgs)
  • InputElement.OnTextInput(TextInputEventArgs)
  • InputElement.OnPointerEntered(PointerEventArgs)
  • InputElement.OnPointerExited(PointerEventArgs)
  • InputElement.OnPointerMoved(PointerEventArgs)
  • InputElement.OnPointerPressed(PointerPressedEventArgs)
  • InputElement.GetNextTabStopOverride()
  • InputElement.GetPreviousTabStopOverride()
  • InputElement.GetFirstFocusableElementOverride()
  • InputElement.GetLastFocusableElementOverride()
  • InputElement.OnPointerCaptureLost(PointerCaptureLostEventArgs)
  • InputElement.ProcessTabStopOverride(IInputElement, IInputElement, bool, bool, ref IInputElement)
  • InputElement.ProcessCandidateTabStopOverride(IInputElement, IInputElement, IInputElement, bool, ref IInputElement)
  • InputElement.OnPointerWheelChanged(PointerWheelEventArgs)
  • InputElement.OnTapped(TappedEventArgs)
  • InputElement.OnRightTapped(TappedEventArgs)
  • InputElement.OnDoubleTapped(TappedEventArgs)
  • InputElement.OnHolding(HoldingRoutedEventArgs)
  • InputElement.UpdateIsEffectivelyEnabled()
  • InputElement.GetIsHoldingEnabled(StyledElement)
  • InputElement.SetIsHoldingEnabled(StyledElement, bool)
  • InputElement.GetIsHoldWithMouseEnabled(StyledElement)
  • InputElement.SetIsHoldWithMouseEnabled(StyledElement, bool)
  • InputElement.Focusable
  • InputElement.IsEnabled
  • InputElement.Cursor
  • InputElement.IsKeyboardFocusWithin
  • InputElement.IsFocused
  • InputElement.IsHitTestVisible
  • InputElement.IsPointerOver
  • InputElement.IsTabStop
  • InputElement.IsEffectivelyEnabled
  • InputElement.TabIndex
  • InputElement.KeyBindings
  • InputElement.IsEnabledCore
  • InputElement.GestureRecognizers
  • InputElement.GotFocus
  • InputElement.GettingFocus
  • InputElement.LostFocus
  • InputElement.LosingFocus
  • InputElement.KeyDown
  • InputElement.KeyUp
  • InputElement.TextInput
  • InputElement.TextInputMethodClientRequested
  • InputElement.PointerEntered
  • InputElement.PointerExited
  • InputElement.PointerMoved
  • InputElement.PointerPressed
  • InputElement.PointerReleased
  • InputElement.PointerCaptureLost
  • InputElement.PointerWheelChanged
  • InputElement.ContextRequested
  • InputElement.ContextCanceled
  • InputElement.Pinch
  • InputElement.PinchEnded
  • InputElement.PullGesture
  • InputElement.PullGestureEnded
  • InputElement.ScrollGesture
  • InputElement.ScrollGestureInertiaStarting
  • InputElement.ScrollGestureEnded
  • InputElement.PointerTouchPadGestureMagnify
  • InputElement.PointerTouchPadGestureRotate
  • InputElement.SwipeGesture
  • InputElement.SwipeGestureEnded
  • InputElement.PointerTouchPadGestureSwipe
  • InputElement.Tapped
  • InputElement.RightTapped
  • InputElement.Holding
  • InputElement.DoubleTapped
  • Interactive.AddHandler(RoutedEvent, Delegate, RoutingStrategies, bool)
  • Interactive.AddHandler<TEventArgs>(RoutedEvent<TEventArgs>, EventHandler<TEventArgs>, RoutingStrategies, bool)
  • Interactive.RemoveHandler(RoutedEvent, Delegate)
  • Interactive.RemoveHandler<TEventArgs>(RoutedEvent<TEventArgs>, EventHandler<TEventArgs>)
  • Interactive.RaiseEvent(RoutedEventArgs)
  • Interactive.BuildEventRoute(RoutedEvent)
  • Layoutable.DesiredSizeProperty
  • Layoutable.WidthProperty
  • Layoutable.HeightProperty
  • Layoutable.MinWidthProperty
  • Layoutable.MaxWidthProperty
  • Layoutable.MinHeightProperty
  • Layoutable.MaxHeightProperty
  • Layoutable.MarginProperty
  • Layoutable.HorizontalAlignmentProperty
  • Layoutable.VerticalAlignmentProperty
  • Layoutable.UseLayoutRoundingProperty
  • Layoutable.UpdateLayout()
  • Layoutable.ApplyTemplate()
  • Layoutable.Measure(Size)
  • Layoutable.Arrange(Rect)
  • Layoutable.InvalidateMeasure()
  • Layoutable.InvalidateArrange()
  • Layoutable.AffectsMeasure<T>(params AvaloniaProperty[])
  • Layoutable.AffectsArrange<T>(params AvaloniaProperty[])
  • Layoutable.MeasureOverride(Size)
  • Layoutable.ArrangeCore(Rect)
  • Layoutable.ArrangeOverride(Size)
  • Layoutable.OnMeasureInvalidated()
  • Layoutable.OnVisualParentChanged(Visual, Visual)
  • Layoutable.Width
  • Layoutable.Height
  • Layoutable.MinWidth
  • Layoutable.MaxWidth
  • Layoutable.MinHeight
  • Layoutable.MaxHeight
  • Layoutable.Margin
  • Layoutable.HorizontalAlignment
  • Layoutable.VerticalAlignment
  • Layoutable.DesiredSize
  • Layoutable.IsMeasureValid
  • Layoutable.IsArrangeValid
  • Layoutable.UseLayoutRounding
  • Layoutable.EffectiveViewportChanged
  • Layoutable.LayoutUpdated
  • Visual.BoundsProperty
  • Visual.ClipToBoundsProperty
  • Visual.ClipProperty
  • Visual.IsVisibleProperty
  • Visual.OpacityProperty
  • Visual.OpacityMaskProperty
  • Visual.CacheModeProperty
  • Visual.EffectProperty
  • Visual.HasMirrorTransformProperty
  • Visual.RenderTransformProperty
  • Visual.RenderTransformOriginProperty
  • Visual.FlowDirectionProperty
  • Visual.VisualParentProperty
  • Visual.ZIndexProperty
  • Visual.GetFlowDirection(Visual)
  • Visual.SetFlowDirection(Visual, FlowDirection)
  • Visual.InvalidateVisual()
  • Visual.AffectsRender<T>(params AvaloniaProperty[])
  • Visual.LogicalChildrenCollectionChanged(object, NotifyCollectionChangedEventArgs)
  • Visual.InvalidateMirrorTransform()
  • Visual.Bounds
  • Visual.ClipToBounds
  • Visual.Clip
  • Visual.IsEffectivelyVisible
  • Visual.IsVisible
  • Visual.Opacity
  • Visual.OpacityMask
  • Visual.CacheMode
  • Visual.Effect
  • Visual.HasMirrorTransform
  • Visual.RenderTransform
  • Visual.RenderTransformOrigin
  • Visual.FlowDirection
  • Visual.ZIndex
  • Visual.VisualChildren
  • Visual.VisualRoot
  • Visual.BypassFlowDirectionPolicies
  • Visual.AttachedToVisualTree
  • Visual.DetachedFromVisualTree
  • StyledElement.DataContextProperty
  • StyledElement.NameProperty
  • StyledElement.ParentProperty
  • StyledElement.TemplatedParentProperty
  • StyledElement.ThemeProperty
  • StyledElement.BeginInit()
  • StyledElement.EndInit()
  • StyledElement.ApplyStyling()
  • StyledElement.InitializeIfNeeded()
  • StyledElement.TryGetResource(object, ThemeVariant, out object)
  • StyledElement.OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs)
  • StyledElement.OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs)
  • StyledElement.OnDataContextChanged(EventArgs)
  • StyledElement.OnDataContextBeginUpdate()
  • StyledElement.OnDataContextEndUpdate()
  • StyledElement.OnInitialized()
  • StyledElement.Name
  • StyledElement.Classes
  • StyledElement.DataContext
  • StyledElement.IsInitialized
  • StyledElement.Styles
  • StyledElement.StyleKey
  • StyledElement.Resources
  • StyledElement.TemplatedParent
  • StyledElement.Theme
  • StyledElement.LogicalChildren
  • StyledElement.PseudoClasses
  • StyledElement.StyleKeyOverride
  • StyledElement.Parent
  • StyledElement.ActualThemeVariant
  • StyledElement.AttachedToLogicalTree
  • StyledElement.DetachedFromLogicalTree
  • StyledElement.DataContextChanged
  • StyledElement.Initialized
  • StyledElement.ResourcesChanged
  • StyledElement.ActualThemeVariantChanged
  • Animatable.TransitionsProperty
  • Animatable.OnPropertyChangedCore(AvaloniaPropertyChangedEventArgs)
  • Animatable.Transitions
  • AvaloniaObject.CheckAccess()
  • AvaloniaObject.VerifyAccess()
  • AvaloniaObject.ClearValue(AvaloniaProperty)
  • AvaloniaObject.ClearValue<T>(AvaloniaProperty<T>)
  • AvaloniaObject.ClearValue<T>(StyledProperty<T>)
  • AvaloniaObject.ClearValue<T>(DirectPropertyBase<T>)
  • AvaloniaObject.Equals(object)
  • 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(AvaloniaProperty, object, BindingPriority)
  • AvaloniaObject.SetValue<T>(StyledProperty<T>, T, BindingPriority)
  • AvaloniaObject.SetValue<T>(DirectPropertyBase<T>, T)
  • AvaloniaObject.SetCurrentValue(AvaloniaProperty, object)
  • AvaloniaObject.SetCurrentValue<T>(StyledProperty<T>, T)
  • AvaloniaObject.Bind(AvaloniaProperty, BindingBase)
  • AvaloniaObject.Bind(AvaloniaProperty, IObservable<object>, BindingPriority)
  • AvaloniaObject.Bind<T>(StyledProperty<T>, IObservable<object>, BindingPriority)
  • AvaloniaObject.Bind<T>(StyledProperty<T>, IObservable<T>, BindingPriority)
  • AvaloniaObject.Bind<T>(StyledProperty<T>, IObservable<BindingValue<T>>, BindingPriority)
  • AvaloniaObject.Bind<T>(DirectPropertyBase<T>, IObservable<object>)
  • AvaloniaObject.Bind<T>(DirectPropertyBase<T>, IObservable<T>)
  • AvaloniaObject.Bind<T>(DirectPropertyBase<T>, IObservable<BindingValue<T>>)
  • AvaloniaObject.CoerceValue(AvaloniaProperty)
  • AvaloniaObject.RaisePropertyChanged<T>(DirectPropertyBase<T>, T, T)
  • AvaloniaObject.SetAndRaise<T>(DirectPropertyBase<T>, ref T, T)
  • AvaloniaObject.InheritanceParent
  • AvaloniaObject.this[AvaloniaProperty]
  • AvaloniaObject.this[IndexerDescriptor]
  • AvaloniaObject.Dispatcher
  • AvaloniaObject.PropertyChanged
  • object.GetType()
  • object.MemberwiseClone()
  • object.ToString()
  • object.Equals(object, object)
  • object.ReferenceEquals(object, object)

Extension Methods