From 6e26cd58fa6d7324484a4766da03b2bdc1c91eb7 Mon Sep 17 00:00:00 2001 From: ReeJK Date: Tue, 13 Apr 2021 13:37:04 +0300 Subject: [PATCH] Button state update when CommandParameter changed --- src/Avalonia.Controls/Button.cs | 13 ++++++++ .../ButtonTests.cs | 33 +++++++++++++++---- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/src/Avalonia.Controls/Button.cs b/src/Avalonia.Controls/Button.cs index 6093cbd581..6ebbfd05f6 100644 --- a/src/Avalonia.Controls/Button.cs +++ b/src/Avalonia.Controls/Button.cs @@ -89,6 +89,7 @@ namespace Avalonia.Controls { FocusableProperty.OverrideDefaultValue(typeof(Button), true); CommandProperty.Changed.Subscribe(CommandChanged); + CommandParameterProperty.Changed.Subscribe(CommandParameterChanged); IsDefaultProperty.Changed.Subscribe(IsDefaultChanged); IsCancelProperty.Changed.Subscribe(IsCancelChanged); } @@ -380,6 +381,18 @@ namespace Avalonia.Controls } } + /// + /// Called when the property changes. + /// + /// The event args. + private static void CommandParameterChanged(AvaloniaPropertyChangedEventArgs e) + { + if (e.Sender is Button button) + { + button.CanExecuteChanged(button, EventArgs.Empty); + } + } + /// /// Called when the property changes. /// diff --git a/tests/Avalonia.Controls.UnitTests/ButtonTests.cs b/tests/Avalonia.Controls.UnitTests/ButtonTests.cs index 7ad0e480c6..c9ad24e654 100644 --- a/tests/Avalonia.Controls.UnitTests/ButtonTests.cs +++ b/tests/Avalonia.Controls.UnitTests/ButtonTests.cs @@ -269,6 +269,19 @@ namespace Avalonia.Controls.UnitTests Assert.Equal(0, command.SubscriptionCount); } + [Fact] + public void Button_Invokes_CanExecute_When_CommandParameter_Changed() + { + var command = new TestCommand(p => p is bool value && value); + var target = new Button { Command = command }; + + target.CommandParameter = true; + Assert.True(target.IsEffectivelyEnabled); + + target.CommandParameter = false; + Assert.False(target.IsEffectivelyEnabled); + } + private class TestButton : Button, IRenderRoot { public TestButton() @@ -324,12 +337,22 @@ namespace Avalonia.Controls.UnitTests private class TestCommand : ICommand { + private readonly Func _canExecute; + private readonly Action _execute; private EventHandler _canExecuteChanged; - private bool _enabled; + private bool _enabled = true; - public TestCommand(bool enabled) + public TestCommand(bool enabled = true) { _enabled = enabled; + _canExecute = _ => _enabled; + _execute = _ => { }; + } + + public TestCommand(Func canExecute, Action execute = null) + { + _canExecute = canExecute; + _execute = execute ?? (_ => { }); } public bool IsEnabled @@ -353,11 +376,9 @@ namespace Avalonia.Controls.UnitTests remove { _canExecuteChanged -= value; --SubscriptionCount; } } - public bool CanExecute(object parameter) => _enabled; + public bool CanExecute(object parameter) => _canExecute(parameter); - public void Execute(object parameter) - { - } + public void Execute(object parameter) => _execute(parameter); } } }