using System.Windows.Input;
using Avalonia.Controls;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace Avalonia.Xaml.Interactions.Custom;
///
///
///
public abstract class ExecuteCommandBehaviorBase : AttachedToVisualTreeBehavior
{
///
///
///
public static readonly StyledProperty CommandProperty =
AvaloniaProperty.Register(nameof(Command));
///
///
///
public static readonly StyledProperty CommandParameterProperty =
AvaloniaProperty.Register(nameof(CommandParameter));
///
///
///
public static readonly StyledProperty FocusTopLevelProperty =
AvaloniaProperty.Register(nameof(FocusTopLevel));
///
///
///
public static readonly StyledProperty FocusControlProperty =
AvaloniaProperty.Register(nameof(CommandParameter));
///
///
///
public static readonly StyledProperty SourceControlProperty =
AvaloniaProperty.Register(nameof(SourceControl));
///
///
///
public ICommand? Command
{
get => GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
///
///
///
public object? CommandParameter
{
get => GetValue(CommandParameterProperty);
set => SetValue(CommandParameterProperty, value);
}
///
///
///
public bool FocusTopLevel
{
get => GetValue(FocusTopLevelProperty);
set => SetValue(FocusTopLevelProperty, value);
}
///
///
///
[ResolveByName]
public Control? FocusControl
{
get => GetValue(FocusControlProperty);
set => SetValue(FocusControlProperty, value);
}
[ResolveByName]
public Control? SourceControl
{
get => GetValue(SourceControlProperty);
set => SetValue(SourceControlProperty, value);
}
///
///
///
///
protected virtual bool ExecuteCommand()
{
if (!IsEnabled)
{
return false;
}
if (AssociatedObject is not { IsVisible: true, IsEnabled: true })
{
return false;
}
if (Command?.CanExecute(CommandParameter) != true)
{
return false;
}
if (FocusTopLevel)
{
Dispatcher.UIThread.Post(() => (AssociatedObject?.GetVisualRoot() as TopLevel)?.Focus());
}
if (FocusControl is { } focusControl)
{
Dispatcher.UIThread.Post(() => focusControl.Focus());
}
Command.Execute(CommandParameter);
return true;
}
}