100 lines
3.4 KiB
C#

using System.Windows.Input;
namespace gehGassi.Toolkit.Views.ContentButton
{
/// <summary>
/// Button der einen beliebigen Inhalt haben kann
/// </summary>
[ContentProperty(nameof(Content))]
public class ContentButton : ContentView, IContentButton
{
private const string PressedState = "Pressed";
/// <summary>
/// Event der ausgelöst wird, wenn der Button geklickt wird
/// </summary>
public event EventHandler Clicked;
/// <summary>
/// Event der ausgelöst wird, wenn der Button gedrückt wird
/// </summary>
public event EventHandler<ContentButtonEventArgs> Pressed;
/// <summary>
/// Event der ausgelöst wird wenn der Button losgelassen wird
/// </summary>
public event EventHandler<ContentButtonEventArgs> Released;
public static readonly BindableProperty CommandProperty = BindableProperty.Create(nameof(Command), typeof(ICommand), typeof(ContentButton), defaultValue: null);
public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create(nameof(CommandParameter), typeof(object), typeof(ContentButton), defaultValue: null);
/// <summary>
/// Command das bei Klick ausgeführt werden soll
/// </summary>
public virtual ICommand Command
{
get => (ICommand)GetValue(CommandProperty);
set => SetValue(CommandProperty, value);
}
/// <summary>
/// Optinaler Command-Parameter
/// </summary>
public virtual object CommandParameter
{
get => GetValue(CommandParameterProperty);
set => SetValue(CommandParameterProperty, value);
}
/// <summary>
/// Methode die aufgerufen wird wenn der Button geklickt wird
/// </summary>
public virtual void OnClicked()
{
Clicked?.Invoke(this, EventArgs.Empty);
if (Command?.CanExecute(CommandParameter) == true)
{
Command?.Execute(CommandParameter);
}
}
/// <summary>
/// Methode die aufgerufen wird wenn der Button gedrückt wird
/// </summary>
public virtual void OnPressed(Point pressPosition)
{
VisualStateManager.GoToState(this, PressedState);
Pressed?.Invoke(this, new ContentButtonEventArgs
{
InteractionPosition = pressPosition
});
}
/// <summary>
/// Methode die aufgerufen wurde wenn der Button losgelassen wird
/// </summary>
public virtual void OnReleased(Point releasePosition)
{
GoToDefaultState();
Released?.Invoke(this, new ContentButtonEventArgs
{
InteractionPosition = releasePosition
});
}
/// <summary>
/// Zum Standard-Status des Buttons wechseln
/// </summary>
private void GoToDefaultState()
{
if (!IsEnabled)
VisualStateManager.GoToState(this, VisualStateManager.CommonStates.Disabled);
else if (IsFocused)
VisualStateManager.GoToState(this, VisualStateManager.CommonStates.Focused);
else
VisualStateManager.GoToState(this, VisualStateManager.CommonStates.Normal);
}
}
}