In a WinUi 3 application I created a custom Command that implements both an Executed event and a HasExecuted property with change notification.
I want to design a CustomControl, preferably inheriting from Button that will show an animation once the Executed event is fired or the HasExecuted property becomes true.
Up to now I have come up with this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.UI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
namespace BridgeSystems.Framework.WinUI.Controls;
public class ConfirmButton : Button
{
protected Thickness _cachedMargin;
protected Brush _cachedForeground;
protected Brush _cachedBackground;
protected double _cachedFontSize;
public ConfirmButton()
{
DefaultStyleKey = typeof(ConfirmButton);
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
_cachedMargin = Margin;
_cachedForeground = Foreground;
_cachedFontSize = FontSize;
_cachedBackground = Background;
}
public bool HasBeenExecuted
{
get => (bool)GetValue(HasBeenExecutedProperty);
set => SetValue(HasBeenExecutedProperty, value);
}
public static readonly DependencyProperty HasBeenExecutedProperty =
DependencyProperty.Register(nameof(HasBeenExecuted), typeof(bool), typeof(ConfirmButton), new PropertyMetadata(false, OnExecuted));
private static void OnExecuted(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var button = d as ConfirmButton;
if (button == null) return;
if ((bool)e.NewValue)
{
button.Foreground = new SolidColorBrush(Colors.White);
button.Background = new SolidColorBrush(Colors.Green);
button.FontSize = 20;
}
else
{
button.Foreground = button._cachedForeground;
button.Background = button._cachedBackground;
button.FontSize = button._cachedFontSize;
}
}
}
This works, but the green background is there to stay. I need to implement an animation to make the green background temporary.
Delving deeper into this I found that the implementation above is not the way to go. It should be done by implementing a custom Visual state in the generic.xamlfile. and using GotoVisualStylein the OnExecuted method. But once I start using a style in `generic.xaml the button loses its default behaviour. Is there a way to do this without designing the Button from scratch?
You may want to look into Storyboarded animations. You can create your animation in code or in Xaml, and the preferred approach is to start it in code, in
OnExecuted.