using System.Reactive;
using System.Reactive.Disposables;
using Avalonia.Controls;
using Avalonia.Data;
using Avalonia.Threading;
namespace Avalonia.Xaml.Interactions.Custom;
///
///
///
public class FocusBehavior : DisposingBehavior
{
///
///
///
public static readonly StyledProperty IsFocusedProperty =
AvaloniaProperty.Register(nameof(IsFocused), defaultBindingMode: BindingMode.TwoWay);
///
///
///
public bool IsFocused
{
get => GetValue(IsFocusedProperty);
set => SetValue(IsFocusedProperty, value);
}
///
///
///
///
protected override void OnAttached(CompositeDisposable disposables)
{
if (AssociatedObject is not null)
{
disposables.Add(AssociatedObject.GetObservable(Avalonia.Input.InputElement.IsFocusedProperty)
.Subscribe(new AnonymousObserver(
focused =>
{
if (!focused)
{
SetCurrentValue(IsFocusedProperty, false);
}
})));
disposables.Add(this.GetObservable(IsFocusedProperty)
.Subscribe(new AnonymousObserver(
focused =>
{
if (focused)
{
Dispatcher.UIThread.Post(() => AssociatedObject?.Focus());
}
})));
}
}
}