diff --git a/src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Core/ItemClickBehavior.cs b/src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Core/ItemClickBehavior.cs new file mode 100644 index 00000000..8ce421e5 --- /dev/null +++ b/src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Core/ItemClickBehavior.cs @@ -0,0 +1,70 @@ +// Copyright (c) Microsoft. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +namespace Microsoft.Xaml.Interactions.Core +{ + using System.Windows.Input; + using Windows.UI.Xaml; + using Windows.UI.Xaml.Controls; + using Interactivity; + + /// + /// A behavior that listens for the event on its source and executes a specified command when that event is fired + /// + public sealed class ItemClickBehavior : Behavior + { + /// + /// Gets or sets the instance to invoke when the current behavior is triggered + /// + public ICommand Command { + get => (ICommand)this.GetValue(CommandProperty); + set => this.SetValue(CommandProperty, value); + } + + /// + /// Identifies the property + /// + public static readonly DependencyProperty CommandProperty = DependencyProperty.Register( + nameof(Command), + typeof(ICommand), + typeof(ItemClickBehavior), + new PropertyMetadata(default(ICommand))); + + /// + /// Handles a clicked item and invokes the associated command + /// + /// The current instance + /// The instance with the clicked item + private void HandleItemClick(object sender, ItemClickEventArgs e) + { + if (!(this.Command is ICommand command) || + !command.CanExecute(e.ClickedItem)) + { + return; + } + + command.Execute(e.ClickedItem); + } + + /// + protected override void OnAttached() + { + base.OnAttached(); + + if (this.AssociatedObject != null) + { + this.AssociatedObject.ItemClick += this.HandleItemClick; + } + } + + /// + protected override void OnDetaching() + { + base.OnDetaching(); + + if (this.AssociatedObject != null) + { + this.AssociatedObject.ItemClick -= this.HandleItemClick; + } + } + } +} diff --git a/src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Microsoft.Xaml.Interactions.csproj b/src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Microsoft.Xaml.Interactions.csproj index a8ed3343..c0ff8ffd 100644 --- a/src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Microsoft.Xaml.Interactions.csproj +++ b/src/BehaviorsSDKManaged/Microsoft.Xaml.Interactions/Microsoft.Xaml.Interactions.csproj @@ -139,6 +139,7 @@ +