using System.Reactive; using System.Reactive.Disposables; using Avalonia.Controls; using Avalonia.Data; namespace Avalonia.Xaml.Interactions.Custom; /// /// Observes the bounds of an associated and updates its Width and Height properties. /// public class BoundsObserverBehavior : DisposingBehavior { /// /// Defines the property. /// public static readonly StyledProperty BoundsProperty = AvaloniaProperty.Register(nameof(Bounds), defaultBindingMode: BindingMode.OneWay); /// /// Defines the property. /// public static readonly StyledProperty WidthProperty = AvaloniaProperty.Register(nameof(Width), defaultBindingMode: BindingMode.TwoWay); /// /// Defines the property. /// public static readonly StyledProperty HeightProperty = AvaloniaProperty.Register(nameof(Height), defaultBindingMode: BindingMode.TwoWay); /// /// Gets or sets the bounds of the associated control. This is a styled Avalonia property. /// public Rect Bounds { get => GetValue(BoundsProperty); set => SetValue(BoundsProperty, value); } /// /// Gets or sets the width of the associated control. This is a two-way bound Avalonia property. /// public double Width { get => GetValue(WidthProperty); set => SetValue(WidthProperty, value); } /// /// Gets or sets the height of the associated control. This is a two-way bound Avalonia property. /// public double Height { get => GetValue(HeightProperty); set => SetValue(HeightProperty, value); } /// /// Attaches the behavior to the associated control and starts observing its bounds to update the Width and Height properties accordingly. /// /// A composite disposable used to manage the lifecycle of subscriptions and other disposables. protected override void OnAttached(CompositeDisposable disposables) { if (AssociatedObject is not null) { disposables.Add(this.GetObservable(BoundsProperty) .Subscribe(new AnonymousObserver(bounds => { Width = bounds.Width; Height = bounds.Height; }))); } } }