using Microsoft.Xaml.Behaviors; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace UIShare.Behaviors { //给Border添加双击事件 public class MouseDoubleClickBehavior : Behavior { public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(MouseDoubleClickBehavior), new PropertyMetadata(null)); public ICommand Command { get => (ICommand)GetValue(CommandProperty); set => SetValue(CommandProperty, value); } public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(MouseDoubleClickBehavior), new PropertyMetadata(null)); public object CommandParameter { get => GetValue(CommandParameterProperty); set => SetValue(CommandParameterProperty, value); } protected override void OnAttached() { base.OnAttached(); // 确保 Border 的 Background 不为 null,否则无法触发点击事件 this.AssociatedObject.MouseLeftButtonDown += OnMouseLeftButtonDown; } protected override void OnDetaching() { base.OnDetaching(); this.AssociatedObject.MouseLeftButtonDown -= OnMouseLeftButtonDown; } private void OnMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { // 判断点击次数是否为 2 if (e.ClickCount == 2) { if (Command != null && Command.CanExecute(CommandParameter)) { Command.Execute(CommandParameter); } } } } }